test.html
<html>
<body>
<span> hello Joe</span>
<span> hello Bob</span>
<span> hello Gundam</span>
<span> hello Corn</span>
</body>
</html>
PHP file
$doc = new DOMDocument();
$doc->loadHTMLFile("test.html");
$xpath = new DOMXPath($doc);
$retrieve_data = $xpath->evaluate("//span");
echo $retrieve_data->item(1);
var_dump($retrieve_data->item(1));
var_dump($retrieve_data);
I am trying to use xPath to find the spans and then echo it, but it seems I cannot echo it. I tried dumping it to see if is evaluating properly, and I am not sure what does this output mean:
object(DOMElement)#4 (0) { }
object(DOMNodeList)#7 (0) { }
What does the #4
and #7
mean and what does the parenthesis mean; What is does the syntax mean?
Update:
This is the error I get when I try to echo $retrieve_data;
and $retrieve_data->item(1);
Catchable fatal error: Object of class DOMNodeList could not be converted to string
$xpath->evaluate("//span");
returns a typed result if possible or a DOMNodeList
containing all nodes matching the given XPath expression. In your case, it returns a DOMNodeList
, because your XPath evaluates to four DOMElements
, which are specialized DOMNodes
. Understanding the Node concept when working with any XML, regardless in what language, is crucial.
echo $retrieve_data->item(1);
cannot work, because DOMNodeList::item
returns a DOMNode
and more specifically a DOMElement
in your case. You cannot echo
objects of any kind in PHP, if they do not implement the __toString()
method. DOMElement
doesnt. Neither does DOMNodeList
. Consequently, you get the fatal error that the object could not be converted to string.
To get the DOMElement's values, you either read their nodeValue
or textContent
.
Some DOM examples by me: https://stackoverflow.com/search?q=user%3A208809+dom
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