I have errors when I want to print the result of an evaluate expression with XPath.
$url = $xpath->evaluate('//a/@href', $event); echo $url ;
I have this error : Catchable fatal error: Object of class DOMNodeList could not be converted to string
My code :
<?php
// Get the HTML Source Code
$url='http://www.parisbouge.com/events/2012/05/01/';
$source = file_get_contents($url);
// DOM document Creation
$doc = new DOMDocument;
$doc->loadHTML($source);
// DOM XPath Creation
$xpath = new DOMXPath($doc);
// Get all events
$events = $xpath->query('//li[@class="nom"]');
// Count number of events
printf('There is %d events<br />', $events->length);
// List all events
for($i = 0; $i < ($events->length); $i++) {
$event = $events->item($i);
$url = $xpath->evaluate('//a/@href', $event);
$nom = $xpath->evaluate('//a/text()', $event);
$lieu = $xpath->evaluate('../li[@class="lieu"]/a/text()', $event);
echo "Result : $url $nom $lieu <br/>";
}
?>
Try this to get information about nodes.
// List all events
for($i = 0; $i < ($events->length); $i++) {
$event = $events->item($i);
$url = $xpath->evaluate('.//a/@href', $event);
$nom = $xpath->evaluate('.//a/text()', $event);
$lieu = $xpath->evaluate('../li[@class="lieu"]/a/text()', $event);
$result = '';
if ($url->length > 0) {
$result .= $url->item(0)->value;
}
if ($nom->length > 0) {
$result .= $nom->item(0)->wholeText;
}
if ($lieu->length > 0) {
$result .= $lieu->item(0)->wholeText;
}
echo $result . "<br />";
//echo "Result : " . $url->item(0)->value . ' | ' . $nom->item(0)->wholeText . ' | ' . $lieu->item(0)->wholeText . "<br/>";
}
Don't forget add checking if node exists etc. To check if there is any nodes you can check nodeList lenght or suppres errors how "Gordon" suggested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With