Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get tagname in xml using php

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!

like image 451
Phil Avatar asked May 11 '11 20:05

Phil


People also ask

What is tagName in xml?

The tagName read-only property of the Element interface returns the tag name of the element on which it's called. For example, if the element is an <img> , its tagName property is "IMG" (for HTML documents; it may be cased differently for XML/XHTML documents).

How to get tag name in PHP?

The DOMElement::getElementsByTagName() function is an inbuilt function in PHP which is used to get the elements by tagname. Parameters: This function accepts a single parameter $name which holds the tag name or use * for getting all the tags.

What is DOM document in PHP?

The DOMDocument::getElementsByTagName() function is an inbuilt function in PHP which is used to return a new instance of class DOMNodeList which contains all the elements of local tag name.

What is a tagName?

A tag name is a part of a DOM structure where every element on a page is been defined via tag like input tag, button tag or anchor tag etc. Each tag has multiple attributes like ID, name, value class etc. As far as other locators in Selenium are concerned, we used these attributes values of the tag to locate elements.


2 Answers

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.

like image 175
jisaacstone Avatar answered Oct 16 '22 08:10

jisaacstone


$nodelist = $results->getElementsByTagName('*');
for( $i=0; $i < $nodelist->length; $i++)
    echo $nodelist->item($i)->nodeName;
like image 26
Mel Avatar answered Oct 16 '22 07:10

Mel