从 SimpleXMLElement 中提取内容的困难

问题描述 投票:0回答:1

我有以下 xml:

"soapenv:Server对于输入字符串:"""

我想获取Body>Fault>faultcode,faultstring的内容

但我不知道为什么不起作用

我的源代码:

$xml = "\<?xml version='1.0' encoding='UTF-8'?\>\<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'\>\<soapenv:Body\>\<soapenv:Fault\>\<faultcode\>soapenv:Server\</faultcode\>\<faultstring\>For input string: '\</faultstring\>\<detail /\>\</soapenv:Fault\>\</soapenv:Body\>\</soapenv:Envelope\>";

$xmlObject = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$namespaces = $xmlObject->getNamespaces(true);
$body = $xmlObject->children($namespaces['soapenv'])->Body->Fault->faultcode;
dd($body);

输出:

简单XML元素{#1890}

php xml laravel string
1个回答
0
投票

我认为你的错误在于你如何获得“faultstring”属性。请记住,您正在设置“soapenv”命名空间,而“faultcode”属性没有此命名空间。这是我正在尝试的例子:

<?php

$xml = <<<XML
<?xml version='1.0' encoding='UTF-8'?>
    <soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
        <soapenv:Body>
            <soapenv:Fault>
                <faultcode>soapenv:Server</faultcode>
                <faultstring>For input string</faultstring>
                <detail />
            </soapenv:Fault>
        </soapenv:Body>
    </soapenv:Envelope>
XML;

$xmlObject = simplexml_load_string($xml);
$namespaces = $xmlObject->getNamespaces(true);
$body = $xmlObject->children($namespaces['soapenv'])->Body->Fault;

print_r($body->xpath('faultstring'));

这是结果: 在此输入图片描述

我还给您留下了一个例子,说明我认为如何更容易地从“faultstring”属性获取您需要的值:

<?php

try {
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    $xpath = new DOMXPath($dom);

    // Execute XPath query to get "faultstring" property value
    $faultString = $xpath->evaluate('//soapenv:Fault/faultstring');

    var_dump($faultString->item(0)->nodeValue);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

这是结果:

在此输入图片描述

© www.soinside.com 2019 - 2024. All rights reserved.