在PHP5中解析复杂的XML

时间:2011-09-28 08:32:00

标签: php xml parsing

您好,这是我的第一篇文章。 我正在尝试使用php解析xml,但我坚持使用它

我的xml示例:

<xml xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
     xmlns:rs='urn:schemas-microsoft-com:rowset'
     xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
   <s:ElementType name='row' content='eltOnly' rs:CommandTimeout='30'>
      <s:AttributeType name='ows_LinkTitle' rs:name='Phone Number*' rs:number='1'>
         <s:datatype dt:type='string' dt:maxLength='512' />
      </s:AttributeType>
      <s:AttributeType name='ows_GSM_x0020_PUK' rs:name='GSM PUK' rs:number='2'>
         <s:datatype dt:type='string' dt:maxLength='512' />
      </s:AttributeType>
   </s:ElementType>
</s:Schema>
<rs:data>
   <z:row ows_LinkTitle='628558621183' ows_GSM_x0020_PUK='41016732'/>
   <z:row ows_LinkTitle='628558621181' ows_GSM_x0020_PUK='21783670'/>
</rs:data>
</xml>

我正试图从'z:row'中获取每个值 非常感谢任何帮助。感谢

我正在尝试使用此代码并且它无法正常工作

$xml_all = simplexml_load_string($xmlnya);

echo '<ol>';
foreach ($xml_all->xml->rs->z as $zrow)
{
 echo '<li> ows_LinkTitle: '.$zrow['ows_LinkTitle'];
 echo '</li>';
}
echo '</ol>';

2 个答案:

答案 0 :(得分:2)

下面的代码段假设(固定)XML文档是$xml中的字符串。

<强>的SimpleXML

$xml  = simplexml_load_string($xml);
$rows = $xml->children('rs', TRUE)->data->children('z', TRUE)->row;
foreach ($rows as $row) {
    $attributes = $row->attributes();
    $link_title = (string) $attributes->ows_LinkTitle;
    $gsm_puk    = (string) $attributes->ows_GSM_x0020_PUK;
    var_dump($link_title, $gsm_puk);
}

阅读:SimpleXML usageSimpleXMLElement::children()SimpleXMLElement::attributes()

<强> DOM

$doc = new DOMDocument;
$doc->loadXML($xml);
$rows = $doc->getElementsByTagNameNS('#RowsetSchema', 'row');
foreach ($rows as $row) {
    $link_title = $row->getAttribute('ows_LinkTitle');
    $gsm_puk    = $row->getAttribute('ows_GSM_x0020_PUK');
    var_dump($link_title, $gsm_puk);
}

阅读:DOMDocument::getElementsByTagNameNS()DOMElement::getAttribute()

答案 1 :(得分:0)

修复xml后,您应该查看simpleXML documentation,特别是xpath method