php - simplexml_load_string issue accessing attributes
one text
Solution:
Use the xpath
method to access the custom-attribute
nodes, like this:
<?php
$xml = <<<XML
<?xml version='1.0' standalone='yes'?>
<n10:category xmlns:n10="..." some-id="123">
<n10:name xml:lang="x-default">Name Here</n10:name>
<n10:custom-attributes>
<n10:custom-attribute attribute-id="abc1">1</n10:custom-attribute>
<n10:custom-attribute attribute-id="abc2">false</n10:custom-attribute>
<n10:custom-attribute attribute-id="abc3">false</n10:custom-attribute>
</n10:custom-attributes>
</n10:category>
XML;
$sx = simplexml_load_string($xml);
$sx->registerXPathNamespace('n10', '...');
$customAttributes = $sx->xpath('/n10:category//n10:custom-attribute');
foreach ($customAttributes as $ca) {
echo $ca['attribute-id'] . '<br>';
}
It's important to register the custom namespace to be able to access the nodes belonging to said namespace.
Source