Search code examples
phpxmlnamespacessimplexml

Can't get out namespace attributes of XML


Trying to get out the value from <af:location>value</af:location>. First of all; Yes, I have searched a lot for answers of how to do. Read a lot of questions here on Stackoverflow and tried many codes. But just can't get it to work.

I can't show all attempts I have did, cause I don't remember all things I tried.

Here is a stripped version of the code I'm using:

$xml_dump = Feed::curl_file_get_contents($url);

libxml_use_internal_errors(true);

    if ($xml = simplexml_load_string($xml_dump))
    {

    }

I have for example tried:

  • The namespace parameter 'af' in -> simplexml_load_string($xml_dump, null, 0, 'af', true)
  • $xml->getNamespaces(true)
  • $sxe = new SimpleXMLElement($xml_dump); $namespaces = $sxe->getNamespaces(true);

But none of them works.

The $xml_dump contains this:

<?xml version="1.0"?>
<rss version="2.0" xmlns:af="http://www.example.se/rss">
    <channel>
        <title>RSS Title - Example.se</title>
        <link>http://www.example.se</link>
        <description>A description of the site</description>
        <pubDate>Wed, 24 Feb 2016 12:20:03 +0100</pubDate>


                <item>
                     <title>The title</title>
                     <link>http://www.example.se/2.1799db44et3a9800024.html?id=233068</link>
                     <description>A lot of text. A lot of text. A lot of text.</description>
                     <guid isPermaLink="false">example.se:item:233068</guid>

                     <pubDate>Wed, 24 Feb 2016 14:55:34 +0100</pubDate>
                     <af:profession>16/5311/5716</af:profession>
                     <af:location>1/160</af:location>

                </item>
  </channel>
</rss>

SOLVED!

And the answer is:

$loc = $item->xpath('af:location');
echo $loc[0];

Solution

  • The question is not clear, I have to say. You mentioned about getting value from an element with prefix at the beginning of the question. But seems to try to get a namespace instead in every attempted codes.

    "Trying to get out the value from <af:location>value</af:location>"

    If you mean to get the value from the element mentioned above, then this is one possible way :

    $location = $xml->xpath('//af:location')[0];
    echo $location;
    

    output :

    1/160
    

    If you mean to get the namespace URI by prefix name instead, then using getNamespaces() is the way to go :

    echo $xml->getNamespaces(true)['af'];
    

    output :

    http://www.example.se/rss