PHP DOMDocument gets tag attribute

Hello, I have an api response in xml format with a number of elements, such as:

<item> <title>blah balh</title> <pubDate>Tue, 20 Oct 2009 </pubDate> <media:file date="today" data="example text string"/> </item> 

I want to use DOMDocument to get the data attribute from the media: file tag. My attempt below does not work:

 $xmldoc = new DOMDocument(); $xmldoc->load('api response address'); foreach ($xmldoc->getElementsByTagName('item') as $feeditem) { $nodes = $feeditem->getElementsByTagName('media:file'); $linkthumb = $nodes->item(0)->getAttribute('data'); } 

What am I doing wrong? Please, help.

EDIT: For some reason I can’t leave comments. I get an error

  Call to a member function getAttribute() on a non-object 

when i run my code. I also tried

 $nodes = $feeditem->getElementsByTagNameNS('uri','file'); $linkthumb = $nodes->item(0)->getAttribute('data'); 

where uri is the uri related to the media namespace (NS), but again the same problem.

Please note that the multimedia element has a form, but I do not think that this is part of the problem, since I usually do not parse the question for attibutes.

+6
dom php parsing domdocument xml-namespaces
source share
2 answers

The example you provided should not generate an error. I tested it and $ linkthumb contained the string “sample text string” as expected

Make sure the media namespace is specified in the returned XML, otherwise the DOMDocument will fail.

If you get a specific error, edit your entry to enable it.

Edit:

Try using the following code:

 $xmldoc = new DOMDocument(); $xmldoc->load('api response address'); foreach ($xmldoc->getElementsByTagName('item') as $feeditem) { $nodes = $feeditem->getElementsByTagName('file'); $linkthumb = $nodes->item(0)->getAttribute('data'); echo $linkthumb; } 

You can also look at SimpleXML and Xpath , as reading XML is much easier than DOMDocument.

+8
source share

As an alternative,

 $DOMNode -> attributes -> getNamedItem( 'MyAttribute' ) -> value; 
+3
source share

All Articles