simplexml_load_string value的路径

时间:2015-12-02 16:12:46

标签: php xml soap

我通过SOAP获得不同的XML字符串。

但是我很难用PHP获取XML的值。

XML示例:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
    <GetUserInfoResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">
        <GetUserInfoResult>
            <GetUserInfo>
                <User ID="23" />
            </GetUserInfo>
        </GetUserInfoResult>
    </GetUserInfoResponse>
</soap:Body>
</soap:Envelope>


<?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 xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
     xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
     xmlns:rs='urn:schemas-microsoft-com:rowset'
     xmlns:z='#RowsetSchema'>
                    <rs:data>
                        <z:row ows_ID="128" />
                    </rs:data>
                </listitems>
            </GetListItemsResult>
        </GetListItemsResponse>
    </soap:Body>
</soap:Envelope>

我想得到身份证明。

我试过这样:

$xml_element = simplexml_load_string($responseContent);
$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_ID'][0];

但是大部分时间我都不知道如何获得我的价值。

是否可以显示整个数组或如何获取值的路径?

1 个答案:

答案 0 :(得分:0)

获取'ows_ID'值的方法是使用SimpleXMLElement children方法,并为子元素添加名称空间。

您可以使用attributes方法获取'ows_ID'的值;

例如:

$responseContent = <<<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 xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
     xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
     xmlns:rs='urn:schemas-microsoft-com:rowset'
     xmlns:z='#RowsetSchema'>
                    <rs:data>
                        <z:row ows_ID="128" />
                    </rs:data>
                </listitems>
            </GetListItemsResult>
        </GetListItemsResponse>
    </soap:Body>
</soap:Envelope>
XML;

$xml_element = simplexml_load_string($responseContent);
$name_spaces = $xml_element->getNamespaces(true);

$rows = $xml_element
    ->children($name_spaces['soap'])
    ->Body
    ->children()
    ->GetListItemsResponse
    ->GetListItemsResult
    ->listitems
    ->children($name_spaces['rs'])
    ->children($name_spaces['z']);

foreach ($rows as $row) {
    $ows_ID =  $row->attributes()->ows_ID;
}

Demo