有没有一种简单的方法来解析这个文本&xml服务器响应PHP


Is there an easy way to parse this text & xml server response with PHP?

我正在使用PHP,因为这个服务器响应不是纯XML,我一直在努力将响应转换为变量/数组以供使用。

我只关心XML树中包含的变量。可以有多个容器(如),数量也会有所不同。也可能会有更多的"嵌套"在各种各样的也(我相信)。

服务器响应示例:

HTTP/1.1 200 OK
Date: Wed, 07 Dec 2011 01:02:01 GMT
Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e DAV/2 PHP/5.2.17
X-Powered-By: PHP/5.2.17
Cache-Control: no-store, no-cache, no-transform, must-revalidate, private
Expires: 0
Vary: Accept-Encoding,User-Agent
Content-Length: 90
Connection: close
Content-Type: text/xml
<?xml version="1.0" encoding="UTF-8"?>
<response>
    <var1>AAA</var1>
    <var2>BBB</var2>
    <var3>CCC</var3>
</response>

谢谢。

function xml2array($xml) {
    $xmlary = array();
    $reels = '/<('w+)'s*([^'/>]*)'s*(?:'/>|>(.*)<'/'s*''1's*>)/s';
    $reattrs = '/('w+)=(?:"|'')([^"'']*)(:?"|'')/';
    preg_match_all($reels, $xml, $elements);
    foreach ($elements[1] as $ie => $xx) {
        $xmlary[$ie]["name"] = $elements[1][$ie];
        if ($attributes = trim($elements[2][$ie])) {
            preg_match_all($reattrs, $attributes, $att);
            foreach ($att[1] as $ia => $xx)
                $xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
        }
        $cdend = strpos($elements[3][$ie], "<");
        if ($cdend > 0) {
            $xmlary[$ie]["text"] = substr($elements[3][$ie], 0, $cdend - 1);
        }
        if (preg_match($reels, $elements[3][$ie]))
            $xmlary[$ie]["elements"] = xml2array($elements[3][$ie]);
        else if ($elements[3][$ie]) {
            $xmlary[$ie]["text"] = $elements[3][$ie];
        }
    }
    return $xmlary;
}

您可以使用strstr();

做类似的事情
$h = 'HTTP/1.1 200 OK
Date: Wed, 07 Dec 2011 01:02:01 GMT
Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e DAV/2 PHP/5.2.17
X-Powered-By: PHP/5.2.17
Cache-Control: no-store, no-cache, no-transform, must-revalidate, private
Expires: 0
Vary: Accept-Encoding,User-Agent
Content-Length: 90
Connection: close
Content-Type: text/xml
<?xml version="1.0" encoding="UTF-8"?>
<response>
    <var1>AAA</var1>
    <var2>BBB</var2>
    <var3>CCC</var3>
</response>';
 print_r(strstr($h, "<?xml")); 
// or this even strstr($h, '<?xml version="1.0" encoding="UTF-8"?>'

这将返回原始xml。

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <var1>AAA</var1>
    <var2>BBB</var2>
    <var3>CCC</var3>
</response>

如果您正在使用PHP 5,请使用SimpleXML库从XML字符串创建对象。