【问题标题】:Get img src inside an a href html dom parser在 a href html dom 解析器中获取 img src
【发布时间】:2023-05-13 08:18:01
【问题描述】:

我正在使用下面的代码通过 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>

【问题讨论】:

  • post-thumbnail&lt;div&gt; 包裹&lt;a&gt; 包裹&lt;img&gt;?您需要编写代码来查找 src 属性。

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


【解决方案1】:

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

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

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

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

【讨论】:

  • 以及如何获取
  • 我相信可以做到:$item['imgurl'] = $article-&gt;find('.post-thumbnail a', 0)-&gt;href;