将xml转换为数组,输出不需要的数组
我正在尝试将 xml 转换为关联数组。
foreach($xml->children() as $child)
{
$ages[$child->getName()] = $child;
}
但是,当我打印出这个数组“年龄”时,我得到的输出是“
[Quagmire] => SimpleXMLElement Object
(
[0] => 30
)
我
[Quagmire] => 30
要做什么改变才能获得所需的输出?”
I am trying to convert xml into associative array.
foreach($xml->children() as $child)
{
$ages[$child->getName()] = $child;
}
But when I print out this array 'ages', I am getting output as
[Quagmire] => SimpleXMLElement Object
(
[0] => 30
)
instead of
[Quagmire] => 30
What change do I make to get the desired output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将子项的值从 SimpleXML 对象显式转换为 int。
You can explicitly cast the value of the child from a SimpleXML object to an int.
是的,SimpleXML 对象的问题在于它们不完全是对象。它们实际上是资源。这就是您遇到此问题的原因。几年前,当我尝试序列化 XML 对象以供以后使用时,我遇到了这个问题。
您需要做的是编写一个执行转换的函数。现在通常我会写一个出来,但事实证明 PHP 社区中的许多人已经解决了这个问题并将其发布在 php.net 网站上。
下面的代码来自 http://www.php.net/manual/ en/book.simplexml.php#97555
上面的代码被我稍微清理了一下。我对丑陋的代码感到恼火。不管怎样,尝试一下,祝你好运!
-帕特里克
Yeah the problem with SimpleXML Objects is that they are not entirely objects. They are actually resources. Which is why you run into this issue. I ran into this a few years ago when I was trying to serialize an XML object for later use.
What you need to do is write a function that will do the convert. Now normally I would write one out, but it turns out a number of people in the PHP community have already tackled this problem and posted it on the php.net website.
The below code comes from http://www.php.net/manual/en/book.simplexml.php#97555
The code above was slightly cleaned up by me. I get annoyed by ugly code. Anyway, give that a crack and good luck!
-Patrick