2013-06-04 38 views
0

我正在循環訪問XML文件中的節點值,但無法根據需要獲取輸出。以下是我正在使用的代碼。

PHP:PHP讀取XML輸出爲數組

$xml = simplexml_load_file("file.xml") or die("Error: Cannot create object");   
$result = array(); 
foreach($xml->picture as $item) 
{ 
    $result[] = $item->logo; 
} 

echo '<pre>'; 
print_r($result); 
echo '</pre>'; 



電流輸出:

Array 
(
    [0] => SimpleXMLElement Object 
     (
      [0] => img/a.jpg 
     ) 

    [1] => SimpleXMLElement Object 
     (
      [0] => img/b.jpg 
     ) 

    [2] => SimpleXMLElement Object 
     (
      [0] => img/c.jpg 
     ) 

    ... 
) 



所需的輸出:

Array 
(
    [0] => a.jpg 
    [1] => b.jpg 
    [2] => c.jpg 

    ... 
) 
+0

我想,我的回答幫你解決你的問題。你應該接受它,這樣問題就會被關閉。如果沒有被接受的答案,人們不會點擊你的問題。 – Brian

回答

0

檢查此鏈接了:here

function toArray(SimpleXMLElement $xml) { 
    $array = (array)$xml; 

    foreach (array_slice($array, 0) as $key => $value) { 
     if ($value instanceof SimpleXMLElement) { 
      $array[$key] = empty($value) ? NULL : toArray($value); 
     } 
    } 
    return $array; 
} 
0

指定數組中的環數,你的代碼保持這樣的:

$xml = simplexml_load_file("file.xml") or die("Error: Cannot create object");   
$result = array(); 
$i = 0;//set a variable to loop throw the foreach 
foreach($xml->picture as $item) 
    { 
//assign the variable with the number of the loop in the disired array 
     $result[$i] = $item->logo; 
    } 

echo '<pre>'; 
print_r($result); 
echo '</pre>';