2013-06-04 40 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>';