djdy
djdy

Reputation: 6919

simplexml_load_string issue accessing attributes

My XML looks like this:

<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>
...

To access some-id I call:

$xml = simplexml_load_string(...);
foreach ($xml->attributes() as $key => $value) {
        if ($key == 'some-id') {
            $data['some_id'] = (string) $value;
        }
    }

The above works. However, when I try to access attributes of custom-attribute, I get back values (like 1, false, false in the example above, but I am unable to get what the attribute-id is equal to on each record. I've tried: foreach ... $xml->{'custom-attributes'}->attributes() and it returns null Also, doing var_dump of $xml in the beginning doesn't seem to include the attribute-id at all.

What am I missing?

Upvotes: 0

Views: 30

Answers (1)

Eduardo Galv&#225;n
Eduardo Galv&#225;n

Reputation: 962

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.

Upvotes: 2

Related Questions