这是我的xml文件:
<?xml version="1.0" encoding="utf-8" ?>
<documentElement>
<rows>
<row>
<column>1</column>
<column>David</column>
<column>Johnson</column>
</row>
<row>
<column>2</column>
<column>Jack</column>
<column>Nixon</column>
</row>
</rows>
</documentElement>
我想循环遍历各行并将它们添加到一个数组中。我将其传递给simplexml
,然后循环遍历这些对象,但无法做到:
$xml->rows
$xml->rows->row
$xml->row
$xml->column
我该怎么办?
谢谢。
发布于 2012-08-28 07:42:29
这实际上是一个更基本的例子:
$sxml = simplexml_load_string($xml);
foreach($sxml->rows->row as $name => $row)
{
echo $name, ': ', var_dump($row);
}
这将为您提供以下输出:
row: object(SimpleXMLElement)#3 (1) {
["column"]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(5) "David"
[2]=>
string(7) "Johnson"
}
}
row: object(SimpleXMLElement)#5 (1) {
["column"]=>
array(3) {
[0]=>
string(1) "2"
[1]=>
string(4) "Jack"
[2]=>
string(5) "Nixon"
}
你可以在这里找到一个在线演示:http://codepad.org/CYyQhvnM
你应该看看手册中的简单示例部分,它有一些非常有洞察力的例子,在这里比我的更深入地解释:
无论如何,我希望答案是有帮助的。相关问题包括:
发布于 2012-08-28 07:45:09
如果您更习惯使用数组,还可以将简单的xml转换为数组:
<?php
$xml = simplexml_load_file('./your.xml');
$json = json_encode($xml);
$array = json_decode($json,TRUE);
print_r($array);
/**
*Array
(
[rows] => Array
(
[row] => Array
(
[0] => Array
(
[column] => Array
(
[0] => 1
[1] => David
[2] => Johnson
)
)
[1] => Array
(
[column] => Array
(
[0] => 2
[1] => Jack
[2] => Nixon
)
)
)
)
)
*/
foreach($array['rows']['row'] as $row){
echo 'Id:'.$row['column'][0],
' Firstname:'.$row['column'][1],
' Lastname:'.$row['column'][2].'<br />'.PHP_EOL;
}
/*Result
Id:1 Firstname:David Lastname:Johnson<br />
Id:2 Firstname:Jack Lastname:Nixon<br />
*/
?>
或者是hakra的一个更简洁的例子
<?php
$xml = simplexml_load_file('./test.xml');
$rows = json_decode(json_encode(iterator_to_array($xml->rows->row, 0)), 1);
print_r($rows);
/**
*
Array
(
[0] => Array
(
[column] => Array
(
[0] => 1
[1] => David
[2] => Johnson
)
)
[1] => Array
(
[column] => Array
(
[0] => 2
[1] => Jack
[2] => Nixon
)
)
)
*/
foreach($rows as $row){
echo 'Id:'.$row['column'][0],
' Firstname:'.$row['column'][1],
' Lastname:'.$row['column'][2].'<br />'.PHP_EOL;
}
发布于 2012-08-28 07:38:08
试试$xml->rows[0]->row[0]
https://stackoverflow.com/questions/12154689
复制相似问题