0

I'm using PHP and since this server response is not pure XML I've been struggling with trying to turn the responses into variables/arrays for use.

I'm only concerned with the variable contained in the XML tree. There can be multiple containers (like ) and the will vary in quantity also. There also might me more "nesting" withing the various also (I believe).

Server Response Example:

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>

Thanks.

4

3 回答 3

1
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;
}
于 2011-12-07T08:21:24.920 回答
0

你可以做这样的事情使用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>
于 2011-12-07T08:04:58.797 回答
0

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

于 2011-12-07T09:47:14.393 回答