Page 1 of 1

XML Parsing Problem

Posted: Sat Aug 07, 2010 3:16 pm
by rlobianco
Hi, I'm trying to parse a simple XML file and I must be missing something since its not working.

The XML file looks like this..

<?xml version="1.0"?>
<document id="105405520" checksum="1" timestamp="2010-08-05 11:00:45.000" type="810X-01" version="1.0" production="F" system_id="0">
<invoice id="105405520" order_id="481989129999" date="2010-08-05 11:00:45.000" supplier_number="7164112" type="DR" shipping_date="2010-08-05 11:00:45.000" shipping_amount="7.95" total_amount="31.49">
<address id="1" type="ST" name="JOHN DOE" company=" " address1="123 MAIN ST" address2=" " city="ANYWHERE" state="MI" postal_code="48236" country="USA"/>
<address id="2" type="BT" name="Company Name" address1="12345 SOUTH ST" city="OhSnap" state="NJ" postal_code="08721" country="USA"/>
<line id="1" uom="EA" supplier_sku="3810112" unit_product_item_charges="23.54" line_quantity="1" line_product_item_charges="23.54" line_total_cost="23.54" tracking_number="1Z07109X0301899999" product_id="TBD"/>
</invoice>
</document>

The PHP Code to parse the file is..

Code: Select all

<?php
    $xml =  simplexml_load_file('file.xml') or die ("Unable to load XML file!"); 
    echo "\nID: ". $xml->document->id;
    echo "\nOrder#: ". $xml->invoice->order_id;
    echo "\nName: ". $xml->address->name;
?>
What am I doing wrong? It's got to be something simple but for the life of me I cant figure it out. lol.

Re: XML Parsing Problem

Posted: Sat Aug 07, 2010 4:53 pm
by greyhoundcode
Using SimpleXML, an element's attributes are accessed is if they are array keys. Also, you do not need to use the name of the root element:

Code: Select all

// Wrong
echo $xml->document->id;

// Better
echo $xml['id'];

Re: XML Parsing Problem

Posted: Sat Aug 07, 2010 7:06 pm
by rlobianco
Thanks.. That put me on the right track. Heres the posted working code for anyone interested.

Code: Select all

<?php
    $xml =  simplexml_load_file('file.xml') or die ("Unable to load XML file!"); 
    echo "\nID: ". $xml[id];
    echo "\nOrder#: ". $xml->invoice['order_id'];
    echo "\nName: ". $xml->invoice->address['name'];
?>