2013-08-19 53 views
1

好的,我使用SimpleXML来解析RSS提要,并且尽可能多的提要包含嵌入的html,我希望能够隔离嵌入式html中包含的任何图像地址。听起来像一个足够简单的任务,但我遇到了解析来自SimpleXMLElement对象的数据的问题。这是相关的代码。SimpleXMLElement强制转换为字符串不行为字符串

for($i = 0; $i < count($articles); $i++) { 
    foreach($articles[$i] as $feedDeet) { 
     $str = (string)$feedDeet; 
     $result = strpos($str, '"'); 
     if($result === false) { 
      echo 'There are apparently no quotes in this string: '.$str; 
     } 
     $explodedString = explode('"', $str); 
     echo "<br>"; 
     if($explodedString[0] == $str) { 
      echo 'ExplodedString is equal to str. Apparently, once again, the string contains no quotes.'; 
     } 
     echo "<hr>"; 
    } 
} 

在这种情况下,$文章是的SimpleXMLElement对象数组每个代表的RSS文章,并包含表示属性和物品的细节的许多孩子的SimpleXMLElement对象。基本上,我想逐个遍历这些属性,将它们转换为字符串,然后使用任何引号将字符串分解为分隔符(因为任何图像地址都将包含在引号内)。然后,我会解析爆炸阵列并搜索任何看起来是图像地址的字符串。但是,explode()和strpos()都不会像我期望的那样运行。为了让我的意思的例子,上面的代码的输出之一如下:

There are apparently no quotes in this string: <p style="text-align: center;"><img class="alignnone size-full wp-image-243922" alt="gold iPhone Shop Le Monde" src="http://media.idownloadblog.com/wp-content/uploads/2013/08/gold-iPhone-Shop-Le-Monde.jpg" width="593" height="515" /></p> <p>Folks still holding out hope that the gold iPhone rumors aren’t true may want to brace themselves, the speculation has just been confirmed by the Wall Street Journal-owned blog AllThingsD. And given the site’s near perfect (perfect?) track record with predicting future Apple plans, and <a href="http://www.idownloadblog.com/2013/08/16/is-this-apples-gold-colored-iphone-5s/">corroborating evidence</a>, we’d say Apple is indeed going for the gold…(...)<br/>Read the rest of <a href="http://www.idownloadblog.com/2013/08/19/allthingsd-gold-iphone-yes/">AllThingsD confirms gold iPhone coming</a></p> <hr /> <p><small> "<a href="http://www.idownloadblog.com/2013/08/19/allthingsd-gold-iphone-yes/">AllThingsD confirms gold iPhone coming</a>" is an article by <a href="http://www.idownloadblog.com">iDownloadBlog.com</a>. <br/>Make sure to <a href="http://twitter.com/iDownloadBlog">follow us on Twitter</a>, <a href="http://www.facebook.com/iPhoneDownloadBlog">Facebook</a>, and <a href="https://plus.google.com/u/0/b/111910843959038324995/">Google+</a>. </small></p> 
ExplodedString is equal to str. Apparently, once again, the string contains no quotes. 

很抱歉,如果这是一个有点难以阅读,它是逐字从输出复制。

正如你所看到的那样,在所讨论的字符串中有明确的引号,但是strpos返回false,意味着找不到指定的字符串,并且explode正在返回一个包含原始字符串的数组,指定的分隔符无法找到。这里发生了什么?我已经被这个小时困住了,而且我觉得我正在失去理智。

谢谢!

回答

1

你在这里犯的错误是你的调试输出是一个HTML页面,所以你打印的信息被浏览器解释为HTML。看到自己的实际内容,您可能需要查看页面源代码,或者使用<pre>标签保留空白,并htmlspecialchars()添加HTML层逸出:echo '<pre>' . htmlspecialchars($str) . '</pre>';

如果在浏览器中输出的样子<p style="text-align: center;">,那么显然输入已经被HTML实体转义,并且可能实际上看起来像&lt;p style=&quot;text-align: center;&quot;&gt;。虽然&quot;看起来",它不是相同的字符串,所以strpos()不会找到它。

为了消除这个额外的转义层,您可以在处理它之前在字符串上运行html_entity_decode()

+1

是的,就是这样。非常感谢。你已经恢复了我的理智。 –