PHP Dom仅获取第一个元标记

时间:2013-01-05 23:06:11

标签: php parsing dom html-parsing

我是一名初学程序员,正在构建一个应用程序来擦除数据并将数据放入数据库。

我正试图抓一些看起来像这样的东西:

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

感谢您的帮助!

1 个答案:

答案 0 :(得分: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)