我阅读了以下xml文件:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<books uiTotalCount="45" uiTotalPages="2" >
<book title="Book1">
<registrationNumber formatCode="raw">BO1</registrationNumber>
</book>
<book title="Book2">
<registrationNumber formatCode="raw">BO2</registrationNumber>
</book>
</books>
使用以下代码时:
$xmlResponse = file_get_contents('\xml\books.xml', true);
xml = simplexml_load_string($xmlResponse);
var_dump($xml->book);
最后一行仅给出第一个元素:
object(SimpleXMLElement)[3]
public '@attributes' =>
array (size=1)
'title' => string 'Book1' (length=5)
public 'registrationNumber' => string 'BO1' (length=3)`
当我查看var_dump($ xml)时,我可以看到2本书:
object(SimpleXMLElement)[2]
public '@attributes' =>
array (size=2)
'uiTotalCount' => string '45' (length=2)
'uiTotalPages' => string '2' (length=1)
public 'book' =>
array (size=2)
0 =>
object(SimpleXMLElement)[3]
public '@attributes' =>
array (size=1)
...
public 'registrationNumber' => string 'BO1' (length=3)
1 =>
object(SimpleXMLElement)[4]
public '@attributes' =>
array (size=1)
...
public 'registrationNumber' => string 'BO2' (length=3)
任何人都知道我做错了什么?我希望得到所有书籍的完整数组,以便我可以进行jsonify。
答案 0 :(得分:0)
是通过完整的xml编写循环并将XML书籍对象存储在数组中的解决方案吗?
答案 1 :(得分:0)
使用foreach
循环。
在循环中,您可以提取每个book
节点的各个属性和子节点,并使用它们来组装数组。以下是基于您的代码的简单示例:
$xmlResponse = file_get_contents('\xml\books.xml', true);
$xml = simplexml_load_string($xmlResponse);
echo "books: [\n";
$count = 0;
foreach($xml->book as $book) {
echo " {\n";
echo ' "title": "'.$book['title'].'"'.",\n";
echo ' "registration-number": "'.$book->registrationNumber.'"'."\n";
echo " },\n";
}
echo "]\n";
打印:
books: [
{
"title": "Book1",
"registration-number": "BO1"
},
{
"title": "Book2",
"registration-number": "BO2"
},
]
参见 PHP Fiddle
(另请快速查看this tutorial了解更多提示)。