PHP和XML:如何在XML中检索属性

时间:2016-02-08 04:24:45

标签: php xml xml-parsing

这是我的XML:

jsonData.product_display[i] 

我知道我需要使用这样的代码:

<?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>

但我需要知道的是我如何检索描述和单位等属性,比如说formid =&#34; AACU 07&#34;并能够将其分配给两个变量,如$ description和$ unit。

通过一些修改我得到了它的工作:

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

2 个答案:

答案 0 :(得分:1)

您可以使用XPath表达式和 while (start <= end) { if (oddNum(start)) { oddSum += start; oddCount++; } else { evenSum += start; evenCount++; } totalSum += start; productNum *= start; avrgNum = totalSum / end; avrgSum = avrgNum / totalSum; start++; } 的{​​{3}}函数来选择具有特定条件的XML文档过滤的一部分。例如,以下是获取SimpleXML元素的行,item中的任何位置,其中属性$xml值等于formid

"AACU 07"

将目标$item = $xml->xpath("//item[@formid='AACU 07']")[0]; 元素放在变量中,然后您可以通过xpath()轻松获取相应的属性:

item

请参阅此处的工作演示:attributes()

答案 1 :(得分:0)

您可以使用attributes()方法

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

将xml转换为数组

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;
}