我在我的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
...
)
答案 0 :(得分: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;
}
答案 1 :(得分: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>';