Php 使用名称空间提取SimpleXML属性

Php 使用名称空间提取SimpleXML属性,php,xml,soap,simplexml,Php,Xml,Soap,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/XM

我试图显示来自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>
我从来没有收到任何具体的错误。它总是空白的,没有显示任何内容

最终,我需要遍历这些记录以显示它们,或者将它们存储到它们自己的数组中以供以后使用,但我似乎甚至无法响应上面代码中的任何内容。我肯定它可能和多个名称空间有关?或者只是一个基本的打字错误


任何关于这个XML响应的建议都会很好。谢谢大家!

您缺少
元素级别,您获取
标记,然后提取
“urn:com:esi911:webeoc7:api:1.0”
命名空间中的子元素,这将为您提供
元素,因此

echo (string) $result->GetDataResult->data->record[0]->attributes()->dataid;
您可以首先通过单个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;
演示:


注意:您可以更准确地使用类似于
//urn:GetDataResult/urn:data/urn:record
(而不是较短的
//urn:record
)的内容作为XPath查询,以防在接收到的XML中的另一个位置有记录。

这无疑是一种更简单、更简洁的方法。非常感谢。我可以让它像您在演示中使用XML响应作为纯文本变量一样工作。但是,当我在实际代码中使用它,调用一个实时API时,我仍然一无所获。$xml对象是空的,即使xml响应与我上面提供的一样。我正在使用cURL来获取XML响应字符串,该字符串按预期工作(CURLOPT_RETURNTRANSFER为TRUE)。还有什么可能导致它作为一个普通字符串工作,但不是来自cURL的?如果您回显XML,它是完全相同的吗?一定有什么不同的地方。您是否可以发布更多详细信息/解释您在实际代码中所做的操作(通过编辑您的问题)?回显返回的XML的最佳方式?@NetzzJD Just
echo
并共享结果。如果它打印的字符串与您发布的字符串相等,结果应该不会有什么不同(除了字符编码的内容,但我怀疑在这种情况下这会有多大关系)。它与最初共享的字符串相同。但是,我已经在这里替换了实际的title和description属性值以避免混淆。虽然没有特殊的角色。我可以使用您的演示链接,将$xmlString完全替换为真实的XML,这样代码就可以工作了。如果我复制/粘贴回显的XML并将其封装在一个普通的硬编码变量中,而不是直接来自cURL响应,那么我可以在自己的代码中执行同样的操作,这种代码在这种情况下也可以工作。我不知道有什么区别。
$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;