John Edward Law
John Edward Law

Reputation: 121

PHP and XML: How to retrieve attributes in XML

Here is my XML:

<?xml version="1.0" encoding="utf-8" ?>
<items>
  <itemgroup name="ATM" column="1" sort="0">
    <item formid="ATM 01" description="Option Teller Balance Sheet - ATM Dept. Ordering ONLY" unit="cello 500"/>
  </itemgroup>
  <itemgroup name="Data Processing" column="1">
    <item formid="AACU 01" description="Receipt Voucher - 2 Part" unit="3600/box"/>
    <item formid="AACU 04" description="Contract Collection Statement" unit="as Req."/>
    <item formid="AACU 07" description="1-part Receipt Voucher - Cont. feed form" unit="5000/box"/>
    <item formid="AACU 08" description="Share IRA Certificate" unit="2200/box"/>
    <item formid="AACU 15" description="PTA PIN MAILER" unit="1800/box"/>
    <item formid="AACU 15B" description="ONLINE ACCESS PIN MAILER" unit="2500/box"/>
  </itemgroup>
</items>

I know I need to use code such as this:

$xml_file = "aacu-data.xml";
$xml = simplexml_load_file($xml_file);

but what I need to know is how I can retrieve attributes such as description and unit for say where formid="AACU 07" and be able to assign it to two variables such as $description and $unit.

WITH SOME MODIFICATIONS I got it to work:

$xml_file = "aacu-data.xml";
$xml = simplexml_load_file($xml_file);

foreach($xml->itemgroup as $itemgroup) {
    foreach($itemgroup->children() as $items) {

        echo $items->attributes()->formid . "<br>";
        echo $items->attributes()->description . "<br>";
        echo $items->attributes()->unit . "<br>";

    }
}:

Upvotes: 1

Views: 85

Answers (2)

har07
har07

Reputation: 89325

You can use XPath expression and SimpleXML's xpath() function, to select part of an XML document filtering with certain criteria. For example, the following is a line to get item element, anywhere in $xml, where attribute formid value equals "AACU 07" :

$item = $xml->xpath("//item[@formid='AACU 07']")[0];

Having the target item element in variable, you can then easily get the corresponding attributes via attributes() :

$description = $item->attributes()->description;
$unit = $item->attributes()->unit;

See working demo here : https://eval.in/514618

Upvotes: 1

Hari Darshan
Hari Darshan

Reputation: 1920

You can access value using attributes() method

foreach($xml->itemgroup[1]->attributes() as $a => $b) {
    ....
}

To Convert xml to array

function xml2array($xmlObject){

    $out = array();

    foreach ( (array) $xmlObject as $index => $node ){  
        if( is_object($node) and empty($node)){
            $out[$index] = '';
        }else{
            $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
        }
    }
    return $out;
}

Upvotes: 0

Related Questions