PHP – 解析SOAP响应中的数据

我正在使用W3验证器API,我得到了这样的响应:

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Body>
<m:markupvalidationresponse env:encodingStyle="http://www.w3.org/2003/05/soap-encoding" xmlns:m="http://www.w3.org/2005/10/markup-validator">

    <m:uri>http://myurl.com/</m:uri>
    <m:checkedby>http://validator.w3.org/</m:checkedby>
    <m:doctype>-//W3C//DTD XHTML 1.1//EN</m:doctype>
    <m:charset>utf-8</m:charset>
    <m:validity>false</m:validity>
    <m:errors>
        <m:errorcount>1</m:errorcount>
        <m:errorlist>

            <m:error>
                <m:line>7</m:line>
                <m:col>80</m:col>
                <m:message>character data is not allowed here</m:message>
                <m:messageid>63</m:messageid>
                <m:explanation>  <![CDATA[
                 PAGE HTML IS HERE
                  ]]>
                </m:explanation>
                <m:source><![CDATA[ HTML AGAIN ]]></m:source>
            </m:error>

            ...

        </m:errorlist>
    </m:errors>
    <m:warnings>
        <m:warningcount>0</m:warningcount>
        <m:warninglist>


        </m:warninglist>
    </m:warnings>
</m:markupvalidationresponse>
</env:Body>
</env:Envelope>

如何从那里提取一些变量?

我需要有效性,errorcount,如果可能的话,还需要错误列表:line,col和message 🙂

有一个简单的方法来做到这一点?

最佳答案
您可以使用simplexml_load_string将XML字符串加载到SimpleXMLElement中,然后使用XPath查找属性.在使用XPath之前注册registerXPathNamespace涉及的命名空间很重要.

$xml = file_get_contents('example.xml'); // $xml should be the XML source string
$doc = simplexml_load_string($xml);
$doc->registerXPathNamespace('m', 'http://www.w3.org/2005/10/markup-validator');
$nodes = $doc->xpath('//m:markupvalidationresponse/m:validity');
$validity = strval($nodes[0]);
echo 'is valid: ', $validity, "\n";
$nodes = $doc->xpath('//m:markupvalidationresponse/m:errors/m:errorcount');
$errorcount = strval($nodes[0]);
echo 'total errors: ', $errorcount, "\n";
$nodes = $doc->xpath('//m:markupvalidationresponse/m:errors/m:errorlist/m:error');
foreach ($nodes as $node) {
    $nodes = $node->xpath('m:line'); 
    $line = strval($nodes[0]);
    $nodes = $node->xpath('m:col');
    $col = strval($nodes[0]);
    $nodes = $node->xpath('m:message');
    $message = strval($nodes[0]);
    echo 'line: ', $line, ', column: ', $col, ' message: ', $message, "\n";
}

转载注明原文:PHP – 解析SOAP响应中的数据 - 代码日志