Search code examples
phpxmlparsingsimplexmlatom-feed

Simple XML Element fail to parse a <link type=""> string from an .atom file


I've this piece of code taken by a .atom document wrapped with file_get_contents:

<entry>
    <link type="text/html" rel="alternate" href="..."/>
</entry>

My goal is to extract the first URL into the href attribute in the entry tag, i tried to parse with:

$xml = new SimpleXMLElement($XML_file);
$link = $xml->entry[0]->link;
print $link;

But shell does not give me any output.


Solution

  • Did you try? As your link element looks empty.

    <entry>
        <link type="text/html" rel="alternate" href="...">Something</link>
    </entry>
    

    And than your php?

    That is my point, t is exactly what you try to echo. to get attributes

    http://www.php.net/manual/en/simplexmlelement.attributes.php

    $text = '<entry><link type="text/html" rel="alternate" href="..." /></entry>';
    $xml = simplexml_load_string($text);
    $linkAttributes = $xml->link->attributes();
    foreach ($linkAttributes as $key => $value)  {
        echo $key . '::' . $value . PHP_EOL;
    }
    

    outputs:

    type::text/html
    rel::alternate
    href::...