PHP XML cant get values

2019-07-14 12:00发布

问题:

I have a string like this:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<GetListItemsResult>
<listitems>
<rs:data>
   <z:row ows_MetaInfo='128;#' />
</rs:data>
</listitems>
</GetListItemsResult>
</GetListItemsResponse>
</soap:Body>
</soap:Envelope>

I would like to get the value 128.

I already tried simplexml_load_string which is empty.

How can I get this attribute?

回答1:

Namespace is important in soap response. Try below code:

<?php
$xml = '<?xml version = "1.0" encoding = "utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
            <GetListItemsResult>
                <listitems>
                    <rs:data>
                        <z:row ows_MetaInfo=\'128;#\'/>
                    </rs:data>
                </listitems>
            </GetListItemsResult>
        </GetListItemsResponse>
    </soap:Body>
</soap:Envelope>';

$xml_element = simplexml_load_string($xml);
$name_spaces = $xml_element->getNamespaces(true);
$soap = $xml_element->children($name_spaces['soap'])
    ->Body
    ->children($name_spaces['rs'])
    ->GetListItemsResponse
    ->GetListItemsResult
    ->listitems
    ->{'rs:data'}
    ->{'z:row'}['ows_MetaInfo'][0];

echo (string) $soap;
?>