How to get <img> src from CDATA in RSS?

孤街浪徒 提交于 2019-11-30 20:49:06

问题


I am fetching data from RSS feed with Magpie.
$rss[description] contains CDATA with html elements:

<![CDATA[  
<div>  
 <a href='url'>  
  <img src='img_url' alt='aaa' title='bbb' border='0' width='116' height='116'>  
 </a>  
</div>]]>  
Some other text  

How can I fetch "img_url" from this? Is preg_match() the only way? Maybe I can use simpleXML?


回答1:


CDATA you have is a string containing HTML. So first treat it as text, but since this text is meant to contain HTML, parse this text using solution appropriate for parsing HTML.

In other words: use appropriate tool (HTML parser) for the job (parsing HTML).

There are already existing solutions for parsing HTML in PHP - eg. see answers to this questions:

  1. How to parse and process HTML with PHP?
  2. Robust, Mature HTML Parser for PHP.

So, basically, you already are able to get the HTML string from your XML. Now parse the HTML and get source of the image using some of the solutions mentioned above.

Using preg_match() for parsing HTML is not a good idea, as it would need to be very complex to do a simple thing HTML parser is suitable for.




回答2:


You would better not to use regular expressions where you can use proper tools. Something which comes to my mind (although maybe it can be done easier):

$descr = $rss[description]; // String. You have extracted description part from your feed

$dom = new DOMDocument();
$dom->loadHTML($descr); // or you can use loadXML
if (!$dom) {
    die('Error loading HTML string.');
}

$xml = simplexml_import_dom($dom);
$imgSrc = (string)$xml->body->div->a->img['src'];

Here we go. Based on the your example CDATA $imgSrc will be equal to img_url.




回答3:


yes,you should use regex,CDATA means that the data should be treat as normal string without parse,so you should think it as a string..



来源:https://stackoverflow.com/questions/8838742/how-to-get-img-src-from-cdata-in-rss

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!