6

Here is my xml:

<news_item>    
    <title>TITLE</title>
    <content>COTENT.</content>
    <date>DATE</date>
<news_item>

I want to get the names of the tags inside of news_item.

Here is what I have so far:

$dom = new DOMDocument();
$dom->load($file_name);
$results = $dom->getElementsByTagName('news_item');

WITHOUT USING other php libraries like simpleXML, can I get the name of all the tag names (not values) of the children tags?

Example solution

title, content, date

I don't know the name of the tags inside of news_item, only the container tag name 'news_item'

Thanks guys!

Phil
  • 10,948
  • 17
  • 69
  • 101
  • possible duplicate of [How get first level of dom elements by Domdocument PHP?](http://stackoverflow.com/questions/5882433/how-get-first-level-of-dom-elements-by-domdocument-php) – Gordon May 11 '11 at 21:09

3 Answers3

15

Try this:

foreach($results as $node)
{
    if($node->childNodes->length)
    {
        foreach($node->childNodes as $child)
        {
            echo $child->nodeName,', ';
        }
    }
}

Should work. Using something similar currently, though for html not xml.

jisaacstone
  • 4,234
  • 2
  • 25
  • 39
2
$nodelist = $results->getElementsByTagName('*');
for( $i=0; $i < $nodelist->length; $i++)
    echo $nodelist->item($i)->nodeName;
Mel
  • 6,077
  • 1
  • 15
  • 12
  • I am pretty sure this one would have worked, I just implemented the first answer before yours, thanks! – Phil May 12 '11 at 00:27
0

[Previous incorrect answer redacted]

For what it's worth though, there's no cost to using simplexml_import_dom() to make a SimpleXMLElement out of a DOMElement. Both are just object interfaces into an underlying libxml2 data structure. You can even make a change to the DOMElement and see it reflected in the SimpleXMLElement or vice versa. So it doesn't have to be an either/or choice.

squirrel
  • 2,010
  • 14
  • 10