Jump to content

DOM Document getting attribute of a node of zero length


greenheart

Recommended Posts

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');
$answer = $nodes->item(0)->getAttribute('data');
}

 

What am I doing wrong? Please help. Usually it works but I think it doesn't this time because the <media:file /> tag is a little different than normal (node length is zero I think and there is no text inside.

 

Look into DOMDocument::getElementsByTagNameNS  (note the NS at the end) since you're trying to access nodes with a particular namespace (media).

 

$nodes = $feeditem->getElementsByTagNameNS('*', 'file');

(Example uses special value "*" because I don't know the media namespace URI)

I tried that with

 

 

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

 

where uri is the uri relating to the media name space(NS) but it gives the error "Call to a member function getAttribute() on a non-object"

 

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

 

 

Solved it. God knows why but the statement has to be in a for loop

 

foreach($feeditem->getElementsByTagNameNS('uri','file') as $element){

    $linkthumb = $element->getAttribute('data');}

 

Even though there is only ONE instance of <media:file ... /> per feeditem.  :confused:

 

Anyway I don't understand the logic behind that one but eh it works.  ;D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.