Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DOMDocument getting Attribute of Tag

Hello I have an api response in xml format with a series of items such as this:

<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 attribute "data" from the tag "media:file". My attempt below doesn't 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: I can't leave comments for some reason Mark. I get the error

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

when I run my code. I have also tried

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

where uri is the uri relating to the media name space(NS) but again the same problem.

Note that the media element is of the form not I think this is part of the problem, as I generally have no issue parsing for attibutes.

like image 366
David Willis Avatar asked Oct 20 '09 22:10

David Willis


2 Answers

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

Ensure the media namespace is defined in the returned XML otherwise DOMDocument will error out.

If you are getting a specific error, please edit your post to include it

Edit:

Try 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 may also want to look at SimpleXML and Xpath as it makes reading XML much easier than DOMDocument.

like image 80
Mark Avatar answered Oct 05 '22 10:10

Mark


Alternatively,

$DOMNode -> attributes -> getNamedItem( 'MyAttribute' ) -> value;
like image 44
Leprechaun Avatar answered Oct 05 '22 10:10

Leprechaun