2013-01-05 15 views
0

저는 데이터를 긁어 내고 데이터를 데이터베이스에 넣는 응용 프로그램을 작성하는 초보 프로그래머입니다. 나는이처럼 보이는 뭔가를 긁어하려고PHP Dom 첫 번째 메타 태그 얻기

:

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

고마워요!

+0

html 스크래핑을 위해이 라이브러리 (http://simplehtmldom.sourceforge.net/)를 적극 권장합니다. 나는 초급자 였기 때문에 DOM으로 시작했다. 나를 믿어 라. simple_html_dom은 훨씬 쉽고 쉽다. – kirugan

답변

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)을 사용하십시오.