Given this XML:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<project type="residential">
<item>
<description><![CDATA[Node 1 text]]></description>
</item>
<item>
<description><![CDATA[Node 2 text]]></description>
</item>
</project>
</root>
XML;
?>
I would like to list the content of all of the of the fields.
This is what I have. It fails with an error “member function xpath() on a non-object”.
// load xml file
include 'xml/portfolio_xml.php';
$portfolio = simplexml_load_string($xml);
foreach ($portfolio->xpath('//project[@type="residential"]/item') as $item) {
echo $item->description;
}
UPDATE
Actually, this example does work. Obviously pulling the sample out of the context of the rest of my application was what I needed.
You need to check that
simple_xml_load_stringsucceeded. Its failing right now because$portfolioisnt an object.This is partially why i prefer using the real constructor instead of the function. I prefer to catch exceptions and handle errors that way:
This way not only can you handle the error but you can take specific action based on the Exception type, code, message, or all of the above.
Additionally, depending on the type of errors you may want to keep them internal to libxml.