0

私は、データをスクレイピングしてデータベースにデータを入れるアプリケーションを構築している初心者プログラマーです。

私は次のようなものをこすり取ろうとしています:

<meta property="og:image" content="image_url_1">
<meta property="og:image" content="image_url_2">

最初のメタ タグのコンテンツが必要ですが、2 番目のコンテンツは必要ありません。現在、$meta_og_image の値は 2 番目のメタ タグの内容です。これが私の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 に答える