Search code examples
phpxmlsimplexml

PHP XML data missing custom attribute data


I have custom XML of the following format:

<xml>
    <data>
        <node index='0.04, 0.17, 0.30, 0.43, 1.48, 2.01, 4.23, 4.36'>
            node data#1
        </node>
        <node index='0.07, 0.20, 0.33, 0.46, 1.51, 2.04, 4.27, 4.40'>
            node data#2
        </node>
        <node index='0.11, 0.24, 0.37, 0.50, 1.55, 2.08, 4.30, 4.43'>
            node data#3
        </node>
    </data>
</xml>

I'm using the following simple PHP code to read the XML file:

$file = 'test1.xml';
    if(file_exists($file) ){
        print "XML file found!";
        $xml = file_get_contents($file) or die('<br>Error loading XML file');
        $xml = simplexml_load_string($xml) or die('<br>Error loading XML file');
    }else{
        print "No XML file found!";
    }

    if($xml){
        print "<pre>";
        print_r($xml);
        print "</pre>";
    }

The output from my code shows SimpleXMLElement Object XML output as expected except that my index attributes data from the source XML is missing. The output looks like the following:

[data] => SimpleXMLElement Object
(
    [node] => Array
        (
            [0] => 
                node data#1
            [1] => 
                node data#2
            [2] => 
                node data#3
        )
)

It's completely missing my node index attributes data.


Solution

  • No, it's just not inside the print_r() but you can access them, its not missing:

    $xml_string = <<<XML
    <xml>
        <data>
            <node index='0.04, 0.17, 0.30, 0.43, 1.48, 2.01, 4.23, 4.36'>
                node data#1
            </node>
            <node index='0.07, 0.20, 0.33, 0.46, 1.51, 2.04, 4.27, 4.40'>
                node data#2
            </node>
            <node index='0.11, 0.24, 0.37, 0.50, 1.55, 2.08, 4.30, 4.43'>
                node data#3
            </node>
        </data>
    </xml>
    XML;
    
    $xml = simplexml_load_string($xml_string);
    
    $first_node = $xml->data->node[0];
    $attrs = (string) $first_node->attributes()->index;
    echo $attrs;
    

    Or of course of you want to loop each node:

    $xml = simplexml_load_string($xml_string);
    $nodes = $xml->data->node;
    foreach($nodes as $node) {
        echo (string) $node . '<br/>';
        $attrs = (string) $node->attributes()->index;
        echo $attrs . '<br/>';
        $numbers = explode(', ', $attrs);
        print_r($numbers);
        echo '<hr/>';
    }
    

    Sample Output