PHP DOM : getElementsbyTagName

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I fear that this is a really stupid question but I am really stuck after trying a load of combinations for the last 2 hours. I am trying to pull the NAME out of the XML file

My XML file:

<?xml version="1.0"?> <userdata> <name>John</name> </userdata> 

My php:

  $doc          =  new DOMDocument();   $doc          -> load( "thefile.xml" );   $thename       =  $doc -> getElementsByTagName( "name" ); $myname= $thename -> getElementsByTagName("name") -> item(0) -> nodeValue; 

The Error:

Catchable fatal error: Object of class DOMElement could not be converted to string in phpreader.php 

I have tried

$myname= $thename -> getElementsByTagName("name") -> item(0) ; $myname= $doc     -> getElementsByTagName("name") -> item(0) -> nodeValue; $myname= $doc     -> getElementsByTagName("name") -> item(0) ; 

but all fail. Guess I have tried just about every combination except the correct one :(

回答1:

You may want $myname = $thename->item(0)->nodeValue. $thename is already the NodeList of all of the nodes whose tag is "name" - you want the first item of these (->item(0)), and you want the value of the node (->nodeValue). $thename should be more appropriately named $names, and you'd see why $names->item(0)->nodeValue makes sense semantically.

This Works For MeTM.



回答2:

This code run:

<?php $xml = <<<XML <?xml version="1.0"?> <userdata>     <name>John</name> </userdata> XML;  $doc = new DOMDocument(); $doc->loadXML($xml); $names = $doc->firstChild->getElementsByTagName("name"); $myname = $names->item(0)->nodeValue;  var_dump($myname); 


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