在一个href html dom解析器中获取img src

时间:2014-04-22 23:46:33

标签: php html-parsing simple-html-dom domparser

我正在使用下面的代码从PHP简单的html dom解析器获取html中的一些数据。 几乎一切都很好......我面临的问题是我无法抓住img src ...我的代码是:

foreach($html->find('article') as $article) {
$item['title']   = $article->find('.post-title', 0)->plaintext;
$item['thumb']   = $article->find('.post-thumbnail', 0)->plaintext;
$item['details'] = $article->find('.entry p', 0)->plaintext;

echo "<strong>img url:</strong> " . $item['thumb'];
echo "</br>";
}

我的帖子结构:

<article class="item-list item_1">
<h2 class="post-title"><a href="http://localhost/mydemosite/category/sports/demo-post" title="mydemo post" rel="bookmark">my demo post 1</a></h2>
<p class="post-meta">
<span class="tie-date">2 mins ago</span>    
<span class="post-comments">
<a href="http://localhost/mydemosite/category/sports/demo-post/#disqus_thread" title="my demo post 1" data-disqus-identifier="1 http://localhost/mydemosite/category/sports/?p=1"></a></span>
</p>
<div class="post-thumbnail">
<a href="http://localhost/mydemosite/category/sports/demo-post/" title="my demo post 1" rel="bookmark">
<img width="300" height="160" src="http://localhost/mydemosite/wp-content/uploads/demo-post-300x160.jpg" class="attachment-tie-large wp-post-image" alt="my demo post 1">
</a>
</div>
<!-- post-thumbnail /-->
<div class="entry">
<p>Hello world... this is a demo post description, so if you want to read more...</p>
<a class="more-link" href="http://localhost/mydemosite/category/sports/demo-post">Read More »</a>
</div>
<div class="clear"></div>
</article>

1 个答案:

答案 0 :(得分:1)

当您使用.post-thumbnail时,您将获得div元素。

要获取img元素的src,请使用:

$item['imgurl']  = $article->find('.post-thumbnail img', 0)->src;

我添加了img选择器并将src直接输出到变量中。