使用命名空间提取 SimpleXML 属性

我正在尝试显示来自 SOAP API 的多条记录。我的电话工作正常,这是预期的 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>

        <GetDataResponse xmlns="urn:com:esi911:webeoc7:api:1.0">

            <GetDataResult>

                <data>

                    <record dataid="6" county="Fayette County" title="Title goes here" description="Description goes here." status="Inactive" />

                    <record dataid="5" county="Caldwell County" title="Title goes here" description="Description goes here." status="Inactive" />

                    <record dataid="4" county="Burnet County" title="Title goes here" description="Description goes here." status="Active" />

                    <record dataid="2" county="Blanco County" title="Title goes here" description="Description goes here." status="Active" />

                    <record dataid="1" county="Bastrop County" title="Title goes here" description="Description goes here." status="Active" />

                </data>

            </GetDataResult>

        </GetDataResponse>

    </soap:Body>

</soap:Envelope>

现在,我只想在我的网页上显示这些记录中的第一个及其属性。我将此响应扔到 SimpleXML 中,并尝试获取要显示的多个属性。这是我迄今为止基于各种其他 StackOverflow 示例所做的尝试,但没有一个真正符合我上面的确切 XML 响应结构:


$xml = simplexml_load_string($response);

$response = $xml->xpath("//soap:Body/*")[0];

$result = $response->children("urn:com:esi911:webeoc7:api:1.0");

echo (string) $result->data->record[0]->attributes()->dataid;

我没有收到任何具体的错误。它总是空白,什么都没有显示。


最终,我需要遍历这些记录以将它们全部显示或将它们存储到自己的数组中以供以后使用,但我似乎什至无法从上面的代码中回显任何内容。我确定这可能与多个名称空间有关?或者只是某个地方的基本错字?


任何有关此 XML 响应的建议都会很棒。谢谢!


浮云间
浏览 113回答 2
2回答

慕莱坞森

您可以先注册命名空间并使用单个 xpath 查询获得所需的结果:$xml = simplexml_load_string($response);$xml->registerXPathNamespace('urn', 'urn:com:esi911:webeoc7:api:1.0');$records = $xml->xpath('//urn:record');echo (string)$records[0]->attributes()->dataid;演示:https ://3v4l.org/f8faC注意:您可以更准确并使用类似//urn:GetDataResult/urn:data/urn:record(而不是更短的//urn:record)作为 XPath 查询,以防您收到的 XML 中的另一个位置可能有记录。

慕雪6442864

您缺少<GetDataResult>元素级别,您获取<soap:Body>标签,然后在"urn:com:esi911:webeoc7:api:1.0"命名空间中提取子项 - 这将为您提供<GetDataResponse>元素,所以......echo&nbsp;(string)&nbsp;$result->GetDataResult->data->record[0]->attributes()->dataid;
打开App,查看更多内容
随时随地看视频慕课网APP