1

I'm using PHP and CURL to get XML, but I'm having problems accessing a specific type of attributes.

Say the XML document is like this:

<item>
    <title>Example Title</title>
    <link>http://www.google.com</link>
    <description>Sample desc here.</description>
    <media:content xmlns:media="http://mediaurl.com/" url="http://www.exampleurl.com/"
    type="image/jpeg" medium="image" height="226" width="571">
    </media:content>
</item>

I want to access the url attribute within the tag, but can't seem to get around the namespace problem.

Currently, I've tried using:

$promos = $item->getElementByTagNameNS("media", "content");
foreach ($promos as $promo)
{
    $promoImage = $promo->getAttribute("url");
    break;
}
echo $promoImage;
3
  • 1
    Does your code actually have a space between for and each? Commented Jul 14, 2011 at 19:34
  • Sorry - not sure how that happened. The actual code does not have issue. Edited above. Thank you for pointing that out. Commented Jul 14, 2011 at 19:42
  • possible duplicate of Parsing XML using PHP Commented Jun 21, 2013 at 23:13

1 Answer 1

1

See http://www.php.net/manual/en/domdocument.getelementsbytagnamens.php. You need to register the namespace with the namespaceURI in your XML and specify it.

ADDED

In the beginning I didn't see you've got xmlns:media attribute in your XML. So all you need to change is line

$promos = $item->getElementsByTagNameNS("http://mediaurl.com/", "content");
Sign up to request clarification or add additional context in comments.

3 Comments

I've tried the instructions on that page nearly word-for-word and haven't even been able to get the document to echo anything. I'm not sure what's wrong. Also, as I mentioned using CURL before, the xml is not hosted on the server this document is working in. Not sure if that's helpful or not. (thanks for responding, by the way)
Please see the content I've added.
Worked beautifully. Thank you so much. I'll go ahead and add your solution to my original post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.