【发布时间】:2013-01-05 23:06:11
【问题描述】:
我是一名初级程序员,正在构建一个用于抓取数据并将数据放入数据库的应用程序。
我正在尝试抓取如下所示的内容:
<meta property="og:image" content="image_url_1">
<meta property="og:image" content="image_url_2">
我想要第一个元标记的内容,而不是第二个的内容。现在 $meta_og_image 的值是第二个元标记的内容。这是我的php代码:
$html = new DOMDocument();
@$html->loadHTML($sites_html);
$meta_og_image = null; //reset
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
if($meta->getAttribute('property')=='og:image'){
//Assign the value from content attribute to $meta_og_image
$meta_og_image = $meta->getAttribute('content');
}
}
echo $meta_og_image;
感谢您的所有帮助!
【问题讨论】:
-
我强烈推荐这个库 (simplehtmldom.sourceforge.net) 用于 html 抓取。我也是从 DOM 开始的,因为我是初学者,相信我 simple_html_dom 更容易更好
标签: php parsing dom html-parsing