0

我正在循环浏览我的 XML 文件中的节点值,但我无法根据需要获得输出。下面是我正在使用的代码。

PHP:

$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

    ...
)
4

2 回答 2

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>';
于 2013-06-04T22:29:53.073 回答
0

检查此链接:这里

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;
}
于 2013-06-04T21:51:00.773 回答