PHP DOM:getElementsbyTagName

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6983738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:44:27  来源:igfitidea点击:

PHP DOM : getElementsbyTagName

phpdom

提问by Morph

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

我担心这是一个非常愚蠢的问题,但在过去 2 小时内尝试了大量组合后,我真的被困住了。我正在尝试从 XML 文件中提取 NAME

My XML file:

我的 XML 文件:

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

My php:

我的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 :(

但都失败了。猜猜我已经尝试过除了正确的组合之外的所有组合:(

回答by Federico Lebrón

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). $thenameshould be more appropriately named $names, and you'd see why $names->item(0)->nodeValuemakes sense semantically.

你可能想要$myname = $thename->item(0)->nodeValue。$thename 已经是其标签为“name”的所有节点的 NodeList - 您需要这些节点中的第一项 ( ->item(0)),并且需要节点的值 ( ->nodeValue)。$thename应该更恰当地命名$names,你会明白为什么$names->item(0)->nodeValue在语义上有意义。

This Works For MeTM.

这对我有用 TM

回答by Morph

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);