我的xml结构如下:
<?xml version="1.0" ?> <user> <name> foo </name> <token> jfhsjfhksdjfhsjkfhksjfsdk </token> <connection> <host> localhost </host> <username> root </username> <dbName> Test </dbName> <dbPass> 123456789 </dbPass> </connection> </user> <user> ... same structure... </user>我制作了这个迭代遍历所有xml节点的代码:
function getConString($node) { $item = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "con"); $nodes = new SimpleXMLElement($item); $result = $nodes[0]; foreach($result as $item => $value) { if($item == "token") { return $value->__toString(); } } }我想要实现的是当$node等于:
jfhsjfhksdjfhsjkfhksjfsdkconnection节点作为数组返回,我怎么能实现呢?
my xml is structured as follow:
<?xml version="1.0" ?> <user> <name> foo </name> <token> jfhsjfhksdjfhsjkfhksjfsdk </token> <connection> <host> localhost </host> <username> root </username> <dbName> Test </dbName> <dbPass> 123456789 </dbPass> </connection> </user> <user> ... same structure... </user>I made this code that iterate through all xml node:
function getConString($node) { $item = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "con"); $nodes = new SimpleXMLElement($item); $result = $nodes[0]; foreach($result as $item => $value) { if($item == "token") { return $value->__toString(); } } }what I'm trying to achieve is that when $node is equal to:
jfhsjfhksdjfhsjkfhksjfsdkthe connection node is returned as array, how I can achieve this?
最满意答案
如果您要解析的XML是您在此处发布的,那么它就是无效的
XML文档必须包含一个根元素,该元素是所有其他元素的父元素:
http://www.w3schools.com/xml/xml_syntax.asp
(你的没有,并且解析这样的字符串失败,出现Exception: String could not be parsed as XML in ... )。
所以你的XML应该是:
<?xml version="1.0" ?> <users> <user> <name> foo </name> <token> jfhsjfhksdjfhsjkfhksjfsdk </token> <connection> <host> localhost </host> <username> root </username> <dbName> Test </dbName> <dbPass> 123456789 </dbPass> </connection> </user> <user> ... same structure... </user> </users>而且您不需要遍历集合
// $nodes is SimpleXMLElement $user = $nodes->user[0]; if($user->token) return $user->token->__toString();If the XML you're trying to parse is what you've posted here, it's invalid since
XML documents must contain one root element that is the parent of all other elements:
http://www.w3schools.com/xml/xml_syntax.asp
(and yours doesn't, and parsing such string fails with Exception: String could not be parsed as XML in ...).
So your XML should be:
<?xml version="1.0" ?> <users> <user> <name> foo </name> <token> jfhsjfhksdjfhsjkfhksjfsdk </token> <connection> <host> localhost </host> <username> root </username> <dbName> Test </dbName> <dbPass> 123456789 </dbPass> </connection> </user> <user> ... same structure... </user> </users>And you don't need to iterate through the collection
// $nodes is SimpleXMLElement $user = $nodes->user[0]; if($user->token) return $user->token->__toString();更多推荐
发布评论