0

我是一名初级程序员,正在构建一个抓取数据并将数据放入数据库的应用程序。

我正在尝试抓取如下所示的内容:

<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;

感谢您的任何帮助!

4

1 回答 1

3

找到第一个循环后,您可以中断循环。

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');
        //stop all iterations in this loop
        break;
    }
}

但是,如果您计划在该循环中定义其他变量,这不是很通用。话虽如此,您可以检查是否$meta_og_image已定义。

foreach($html->getElementsByTagName('meta') as $meta) {
    if($meta->getAttribute('property') == 'og:image' && !isset($meta_og_image)) { 
        //Assign the value from content attribute to $meta_og_image
        $meta_og_image = $meta->getAttribute('content');
    }
}

您必须删除$meta_og_image开头的定义。稍后,如果您检查它是否为 ,请改为null使用!isset($meta_og_image)

于 2013-01-05T23:08:05.907 回答