PHP DOM: getElementsbyTagName

I'm afraid this is a really stupid question, but I really got stuck after trying to load combinations in the last 2 hours. I am trying to pull NAME from an 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;

Error:

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

I tried

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

but everything is failing. I think I tried almost every combination except the correct one :(

+5
source share
2 answers

You might want to $myname = $thename->item(0)->nodeValue. $ thename is already the NodeList of all nodes whose tag is "name" - you need the first element of them ( ->item(0)), and you want to get the value of node ( ->nodeValue). $thenameshould be more appropriately named $names, and you will see why $names->item(0)->nodeValueit makes sense semantically.

TM.

+5

:

<?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);
+3

All Articles