Question

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.

Was it helpful?

Solution

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;
}

OTHER TIPS

You can do something like this using 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"?>'

This would give you the raw xml returned.

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

If you're using PHP 5, use the SimpleXML library to create an object from an XML string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top