greenheart Posted October 20, 2009 Share Posted October 20, 2009 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. Link to comment https://forums.phpfreaks.com/topic/178403-dom-document-getting-attribute-of-a-node-of-zero-length/ Share on other sites More sharing options...
salathe Posted October 21, 2009 Share Posted October 21, 2009 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) Link to comment https://forums.phpfreaks.com/topic/178403-dom-document-getting-attribute-of-a-node-of-zero-length/#findComment-940811 Share on other sites More sharing options...
greenheart Posted October 21, 2009 Author Share Posted October 21, 2009 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. Link to comment https://forums.phpfreaks.com/topic/178403-dom-document-getting-attribute-of-a-node-of-zero-length/#findComment-940817 Share on other sites More sharing options...
greenheart Posted October 21, 2009 Author Share Posted October 21, 2009 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. Anyway I don't understand the logic behind that one but eh it works. Link to comment https://forums.phpfreaks.com/topic/178403-dom-document-getting-attribute-of-a-node-of-zero-length/#findComment-940826 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.