2011-03-22 100 views
3

http://pastie.org/1701923下面是從API中返回的XML我正在查詢郵政編碼。使用PHP SimpleXML處理XML時遇到問題

我想從每個條目中提取數據,並將其直接循環或放入可循環的數組中。我似乎無法做到。下面是我用的是最新的代碼:

$xml = new SimpleXMLElement($results); 
foreach($xml->zipcoderadius->zipcodes as $loc) { 
    $codes[] = (string)$loc['zipcode']; 
} 
print_r($codes); 
die(); 

($結果從CURL返回的XML)

什麼正在被輸出陣列([0] => [1] => [2] => [3] => [4] =>)

回答

0

我想這是,n是一個字符串(zipcode)。嘗試不使用字符串

+0

感謝。沒有變化,結果是Array([0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8 ] => [9] => [10] => [11] => [12] => [13] => [14] => [15] => [18] ] => [19] => [20] => [21] => [22] => [23] => [24] => [25] => [28] => [28 ] => [29] =>) (在調用中使用不同的郵政編碼,因此更多的結果) – 2011-03-23 03:29:03

0

我不確定您是否正確解決了郵政編碼。對我來說,下面的工作,假設你先前將你的cURL結果存儲在$xmlStr中。

$push = array(); 
$foo = simplexml_load_string($xmlStr); 
foreach($foo->zipcoderadius->zipcodes->id as $bar) { 
    array_push($push, (string)$bar); 
} 
print_r($push); 

領導以下的輸出:

Array 
(
    [0] => 75969 
    [1] => 75970 
    [2] => 75971 
) 

順便說一句:在SimpleXML的物體看起來是這樣的:

object(SimpleXMLElement)#1 (1) { 
    ["zipcoderadius"]=> 
    object(SimpleXMLElement)#4 (1) { 
    ["zipcodes"]=> 
    object(SimpleXMLElement)#3 (32) { 
     ["id"]=> 
     array(3) { 
     [0]=> 
     string(5) "75969" 
     [1]=> 
     string(5) "75970" 
     [2]=> 
     string(5) "75971" 
     } 
     ["zipcode"]=> 
     array(3) { 
     [0]=> 
     string(5) "94945" 
     [1]=> 
     string(5) "94945" 
     [2]=> 
     string(5) "94945" 
     } 
...