Search code examples
phpsimplexml

How to parse image out of node using SimpleXML?


I have a feed with images in the description node. How can I parse out just the image URL and just the description text with no line break in between?

<description>&lt;img src='http://example.com/100915gignac-clement_g_70x70.jpg'&gt;&lt;/img&gt;&lt;br /&gt;(Source: Example.com) Québec annonce qu'une autorisation ministérielle sera nécessaire pour une prise de participation de plus de 30&amp;#160;% de la nouvelle société fusionnée Investissement Québec dans une entreprise.</description>

Solution

  • Pass the content of the decription node to another SimpleXmlElement.

    $sxe  = new SimpleXmlElement("<description>&lt;img src='http://example.com/100915gignac-clement_g_70x70.jpg'&gt;&lt;/img&gt;&lt;br /&gt;(Source: Example.com) Québec annonce qu'une autorisation ministérielle sera nécessaire pour une prise de participation de plus de 30&amp;#160;% de la nouvelle société fusionnée Investissement Québec dans une entreprise.</description>");
    $img  = new SimpleXMLElement("<root>$sxe</root>");
    $desc = (string) $img;
    $src  = (string) $img->img['src'];
    
    var_dump($desc, $src);
    

    For some reason, SimpleXML apparently html_decodes the entities by itself.