2011-12-07 120 views
0

我使用PHP,並且由於此服務器響應不是純XML,所以我一直在努力嘗試將響應轉化爲變量/數組以供使用。有沒有一種簡單的方法來解析這個文本和XML服務器響應與PHP?

我只關心包含在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> 

感謝。

回答

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

工作!謝謝!!!這絕對給我一些我可以工作的東西! – Rob

+0

你能解釋一下代碼嗎?什麼是「元素」參數?如果沒有提供,xmlary只是一個空數組no? – Ebpo

+0

@Ebpo查閱['preg_match_all'](http://php.net/manual/en/function.preg-match-all.php)的文檔。該函數使用一組匹配來填充'$ elements'。 –

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> 
+0

啊,完美。謝謝! – Rob

0

如果你使用PHP 5中,使用的SimpleXML庫從XML字符串創建對象。

+0

我試着摸摸它...是無法得到它的工作。 – Rob

+0

使用SimpleXML提供的代碼不起作用,我可以提供幫助。 – Mina

+0

此外,請向我們展示您現有的代碼,以便我們可以從... – Mina

相關問題