PHP DOM:按标签名称获取元素
我担心这是一个非常愚蠢的问题,但在过去两个小时尝试了大量组合后,我真的陷入了困境。我试图从 XML 文件中提取 NAME
我的 XML 文件:
<?xml version="1.0"?>
<userdata>
<name>John</name>
</userdata>
我的 php:
$doc = new DOMDocument();
$doc -> load( "thefile.xml" );
$thename = $doc -> getElementsByTagName( "name" );
$myname= $thename -> getElementsByTagName("name") -> item(0) -> nodeValue;
错误:
Catchable fatal error: Object of class DOMElement could not be converted to string in phpreader.php
我已尝试过
$myname= $thename -> getElementsByTagName("name") -> item(0) ;
$myname= $doc -> getElementsByTagName("name") -> item(0) -> nodeValue;
$myname= $doc -> getElementsByTagName("name") -> item(0) ;
,但都失败了。我猜我已经尝试了几乎所有组合,除了正确的组合:(
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 :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要
$myname = $thename->item(0)->nodeValue
。 $thename 已经是所有标签为“name”的节点的 NodeList - 您想要其中的第一项 (->item(0)
),并且您想要该节点的值(->nodeValue
)。$thename
应该更合适地命名为$names
,你就会明白为什么$names->item(0)->nodeValue
从语义上讲是有意义的。这对我有用TM。
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.
这段代码运行:
This code run: