How to access element like <game:title> with simplexml?

对着背影说爱祢 提交于 2019-12-24 01:43:01

问题


I'm trying to parse XML feed with SimpleXML, here is a chunk of the XML tree:

<item>
<game:name>Tetris</game:name> 
<game:desc>Way Cool Game</game:desc>
<size>5mb</size> 
</item>

Well actually, I can succesfully access 'size' with something like that: $item->size, but how do I get value? Of course I can't call like that: $item->game:name, and I don't know how what goes after ':' is called. Is it a parameter, attribute or what?

Thanks for advance!


回答1:


You need to define the namespace for game. XML requires all namespaces to be defined. There have been several previous answers about using custom namespaces: i.e.

  • How do I parse XML containing custom namespaces using SimpleXML?



回答2:


Use the children() function to get the children of the namespace.

$useThis = $xmlDoc->children("http://game.namespace/");

given that http://game.namespace is the URL to your game namespace in the root node.

Here's an explanation/sample:

  • SimpleXML and namespaces (Oct 2005; by Kevin Yank for Sitepoint)



回答3:


As for the getting the value of a SimpleXMLElement, you just cast it to a string:

$size_value = (string)$item->size;


来源:https://stackoverflow.com/questions/1307459/how-to-access-element-like-gametitle-with-simplexml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!