Search code examples
phpxmlsimplexml

Reading XML short notation in php


My xml looks like this

<?xml version="1.0" standalone="yes"?>

<DATAPACKET Version="2.0">
<METADATA>
<FIELDS>
<FIELD attrname="BRAND" fieldtype="string" WIDTH="15"/>
</FIELDS>
<PARAMS/>
</METADATA>
<ROWDATA>
<ROW BRAND="180S" STYLE="LUSH-EAR-WARMER" BARCODE="10823452061" STORE_PRICE="0.00" OH="12"/>
-----<ROW WITH ATTRIBUTES REPEATS)
------
</ROWDATA>
</DATAPACKET>

I am getting it via a web source through a php script

  1. I want to read each
  2. I want to extract value of BARCODE
  3. I want to extract value of OH

what I have tried is

$xml = simplexml_load_file("final.xml");

    foreach ($xml->DATAPACKET->ROWDATA->ROW as $c) {

        $attrib = $c->attributes();
        echo("<br /><br />");
        echo("Barcode" . $attrib[BARCODE] . "<br />");
        echo("OH:" . $attrib[OH] . "<br />");
        echo "<br/>";
    }

and I get error

Notice: Trying to get property of non-object in...

can somebody help me troubleshoot this and help me solve my issue? thanks a million


Solution

  • You are almost there.

    $xml represents <DATAPACKET>, so don't repeat it, but:

    foreach ($xml->ROWDATA->ROW as $row) {
        echo "$row[BARCODE] <br />";
    }
    

    see it in action: http://3v4l.org/4gWAl