Parsing HTML tags from inside XML in PHP

php, simplexml, xml-parsing

Solution

The description content has its special characters encoded, so it's not treated as nodes within the XML, rather it's just a string. You can decode the special characters, then load the HTML into DOMDocument and do whatever you want to do. For example:

foreach ($rss->channel->item as $item) {
    echo '<h3>'. $item->title . '</h3>'; 

        foreach($item->description as $desc){

            $dom = new DOMDocument();
            $dom->loadHTML(htmlspecialchars_decode((string)$desc));

            $anchors = $dom->getElementsByTagName('a');
            echo $anchors->item(0)->getAttribute('href');
        }
}

XPath is also available for use with DOMDocument, see DOMXPath.

Problem

I'm trying to create my own RSS feed (learning purposes) using `simplexml_load_string` while parsing `http://uk.news.yahoo.com/rss` in PHP. I get stuck at reading the HTML tags inside the `<description>` tag. My code so far looks like this: ``` $feed = file_get_contents('http://uk.news.yahoo.com/rss'); $rss = simplexml_load_string($feed); //for each element in the feed foreach ($rss->channel->item as $item) { echo '<h3>'. $item->title . '</h3>'; foreach($item->description as $desc){ //how to read the href from the a tag??? //this does not work at all $tags = $item->xpath('//a'); foreach ($tags as $tag) { echo $tag['href']; } } } ``` Any ideas how to extract each HTML tag? Thanks

Original source