Parsing complex XML in PHP5
Hello this is my first post. i'm trying to parse an xml using php, but i'm stuck with it
example of my 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:Attri开发者_开发百科buteType 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>
i'm trying to get the value from each of 'z:row' Any help is very appreciated. Thanks
i'm trying this code and it doesnt work
$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>';
The snippets below assume the (fixed) XML document is a string in $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);
}
To read: SimpleXML usage, SimpleXMLElement::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);
}
To read: DOMDocument::getElementsByTagNameNS()
, DOMElement::getAttribute()
.
When you get your xml fixed, you should have a look at the simpleXML documentation and specifically the xpath method.
精彩评论