Search code examples
phpxmlxml-parsingxmlreader

Fetching data from XML incl. children and display in page using php


I have a XML with the following structure:

<item>
                      <attributes>
                <attribute datatype="text">
                    <name><![CDATA[name]]></name>
                    <value><![CDATA[Product Name]]></value>
                </attribute>
                <attribute datatype="text">
                    <name><![CDATA[sku]]></name>
                    <value><![CDATA[PRODUCTSKU]]></value>
                </attribute>
                <attribute datatype="numeric">
                    <name><![CDATA[price]]></name>
                    <value>10000</value>
                </attribute>
        <attribute datatype="numeric">
                    <name><![CDATA[eancode]]></name>
                    <value>123456789</value>
                </attribute>
            </attributes>
        </item>

Now, here I am looking for the following output:

Product Name : PRODUCTSKU : 10000 : 123456789

But with the following code am fetching the whole details under attribute node but I can't segregate the SUB NODES values...

$reader = new XMLReader();
$reader->open( 'test.xml' );
$id = 'attributes';
while ($reader->read()) {
    if ($reader->nodeType == XMLReader::ELEMENT) {
        $exp = $reader->expand();
        if ($exp->nodeName == $id)
            echo "<b>" . $exp->nodeName . " : </b>" . $exp->nodeValue . "<br />";

    }
}

I have also tried this with DOMDOcument also:

$xml = new DOMDocument(); 
$xml->load('test.xml');
$root = $xml->documentElement;
foreach($root->childNodes as $node){

    //print $node->nodeName.' - '.$node->nodeValue;
    print $node->nodeValue;
}

But this also displays all the sub nodes together...I want to segregate them and store into DB...please help me with this...am struggling with this quiet a long


Solution

  • It's easier to use SimpleXML but if you want to use XMLReader try this:

    $values = array();
    $reader = new XMLReader();
    $reader->open( 'test.xml' );
    $id = 'attribute';
    while ($reader->read()) {
        if ($reader->nodeType == XMLReader::ELEMENT) {
            $exp = $reader->expand();
            if ($exp->nodeName == "item") {
                if (count($values)) print implode(" : ", $values);
                $values = array();
            }
            if ($exp->nodeName == $id) {
                foreach ($exp->childNodes as $node) {
                    if ($node->nodeName == "value") {
                        $values[] = $node->textContent;
                    }
                }
            }
        }
    }
    if (count($values)) print implode(" : ", $values);