wakey
wakey

Reputation: 2409

DOM/xpath usage with php to process external site?

I am trying to wrap my head around DOM in order to process an external URL and retrieve a piece of content. So far by looking at some tutorials and such on the interwebs I have come up with this:

$url = 'http://www.staticmapper.com/index.php?system=J224442';

$dom = new DOMDocument;
$dom->loadHTMLfile($url);

$xpath = new DOMXpath($dom);

$elements = $xpath->query("//html/body/table[2]/tbody/tr[1]/td[1]/p[2]/span");

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

  }
}

However, nothing returns.

The desired output in this case would be "J244". Can anyone give me pointers/suggestions on how to achieve this goal?

Thanks.

Upvotes: 1

Views: 416

Answers (1)

user1978142
user1978142

Reputation: 7948

I just did modifications from your code. Just omitted tbody from the query. Consider this example:

$dom = new DOMDocument;
@$dom->loadHTMLFile('http://www.staticmapper.com/index.php?system=J224442');

$xpath = new DOMXpath($dom);
$elements = $xpath->query("/html/body/table[2]/tr[1]/td[1]/p[2]/span");
foreach($elements as $value) {
    echo $value->nodeValue; // J244
}

Sample Output

Upvotes: 2

Related Questions