views:

605

answers:

2

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.

+1  A: 

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.

Mark
That did it, the extra code.Thank you!!
David Willis
A: 

Alternatively,

$DOMNode -> attributes -> getNamedItem( 'MyAttribute' ) -> value;
Leprechaun