Getting this error
Call to a member function attributes() on a non-object
I have found multiple answers to this on SO, but none of them seem to solve my problem?
Here is the XML:
<Routes>
<Route type="source" name="incoming">
</Route>
<Routes>
Here is the PHP:
$doc = new SimpleXMLElement('routingConfig.xml', null, true);
class traverseXML {
function getData() {
global $doc;
$routeCount = count($doc -> xpath("Route")); //this value returns correctly
$routeArr = array();
for ($i = 1; $i <= $routeCount; $i++) {
$name = $doc -> Route[$i] -> attributes() -> name;
array_push($routeArr, $name);
}
return $routeArr;
}
}
$traverseXML = new traverseXML;
var_dump($traverseXML -> getData());
I understand what the error means, but how is it a non-object? How do I return the name attribute of Routes/Route[1] ?
Your
$docis<Routes>. Trying to get->Routesfrom it is trying to getYou need to do
$doc->Route[$i]. Errors like this are less frequent when you name your variable after the document root:Also, your XML is invalid. The Routes element is not closed.
In addition, you don’t need the XPath. SimpleXML is traversable, so you can foreach over all the routes by doing
And
attributes()returns an array, so you cannot chain->nameoff it but must access it with square brackets. But it’s not necessary to useattributes()anyway because you can get attributes from SimpleXmlElements directly via square brackets, e.g.Here is an example that will print “incoming”:
demo
If you want to do it with XPath, you can collect all the attributes in an array like this:
Yes, it’s just that one line 🙂
As for your class:
Don’t use
global. Forget it exists. If you want to have a class, inject the dependency, e.g. dodemo