2016-09-16 2 views
0

다음 두 함수는 URL에서 메타 데이터를 가져 오기 위해 완벽하게 작동합니다. 먼저 웹 페이지의 제목을 얻은 다음 opengraph 설명 태그를 검색합니다. og : 설명을 찾지 못한 경우 메타 설명으로 되돌아갑니다.PHP Curl을 사용하여 페이지의 첫 번째 이미지와 첫 번째 25 단어의 텍스트를 가져옵니다.

내가 원하는 것은 메타 설명이 없으면 텍스트의 처음 25 단어를 가져옵니다.

동일하게 나는 og : image에 폴백 (fall back)을 만들려고합니다. 아무 것도 없으면 페이지에서 찾은 첫 번째 이미지를 움켜 잡습니다.

function file_get_contents_curl($url) 
{ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 

function getit($site) 
{ 
    $content = file_get_contents_curl($site); 
    $doc = new DOMDocument(); 
    @$doc->loadHTML($content); 
    $nodes = $doc->getElementsByTagName('title'); 
    $node = $doc->getElementsByTagName('img'); 
    $title = $nodes->item(0)->nodeValue; 
    $firstimage = $node->item(0)->getAttribute('src'); 
    $metas = $doc->getElementsByTagName('meta'); 

    for ($i = 0; $i < $metas->length; $i++) 
    { 
     $meta = $metas->item($i); 
     if($meta->getAttribute('property') == 'og:description') 
     { 
      $description = $meta->getAttribute('content'); 
     } 
     elseif ($meta->getAttribute('name') == 'description') 
     { 
      $description = $meta->getAttribute('content'); 
     } 
     if($meta->getAttribute('property') == 'og:image') 
     { 
     $image = $meta->getAttribute('content'); 
     } 
    } 
$str .= 'Title: '.$title.' <br/><br/>'; 
$str .= 'Description: '.$description.' <br/><br/>'; 
$str .= 'Image: <img src="'.$image.'">'; 
$str .= 'Image2: <img src="'.$firstimage.'">'; 
echo $str; 
} 

나는 컬을 사용하여 매우 새롭고 전혀 유창 그것입니다, 그래서 난 정말 어디서부터 시작 또는 끝이 일어날 수 있도록하려면 코드를 수정 모른다. 이미지에 대해 binarytransfer가 필요하다고 믿는 바이너리 전송 옵션을 curl setopt에 추가했습니다. 그러나 실제로 여기에서 뭘하고 있는지에 관해선 우둔한데,이 작업을 수행하는 방법에 대한 제안을 주시면 감사하겠습니다.

UPDATES : 나는 위의 코드를 업데이트

바이너리 전송을 제거합니다. 테스트 목적으로 다음

$node = $doc->getElementsByTagName('img'); 
$firstimage = $node->item(0)->getAttribute('src'); 

내가 추가 : 나는 또한 다음과 같은 추가

$str .= 'Image2: <img src="'.$firstimage.'">'; 

그래서 지금은 반환되는 firsst 이미지가 여전히의 처음 25 개 단어를 얻을 호르을 파악해야 페이지의 텍스트.

+0

이미지를 가져 오지 않습니다. 이미지의 바이너리 데이터를 찾을 수있는 위치에 POINTING이라는 URL을 포함하는'src' 속성을 가진'' 태그를 포함하는 HTML을 가져 왔습니다. html은 단지 텍스트이므로 이진 비트는 무의미합니다. –

+0

@MarcB 당신이 말하고있는 것을 바탕으로, $ image = $ doc-> getElementsByTagName ('img'); 그러나 발견 한 첫 번째 이미지로 어떻게 제한합니까? body 태그의 텍스트 중 처음 25 개의 단어가 다른 태그가 아닌지 어떻게 똑같이 얻을 수 있습니까? – Bruce

+0

@Bruce 현재 코드를보고 원하는 것을 수정하는 방법을 알아야합니다.이 코드는'$ body = $ doc-> getElementsByTagName ('body')와 같아야합니다. $ description = $ body-> item (0) -> nodeValue; $ images = $ doc-> getElementsByTagName ('image'); – cmorrissey

답변

0

그래서 25 개의 단어에 대해 첫 번째 단락 태그를 호출하고 그 값을 문자열로 설정 한 다음 문자열을 분해하고 처음 25 개의 단어를 호출했습니다. 나는 이것들을 변수로 설정하여 테스트로 쉽게 echo 할 수 있습니다. 첫 번째 이미지에 대한

, 나는 추가 : 이미지 비어 만약 그렇다면 내가 대신 첫 번째 이미지를 에코 : OG는 경우
$node = $doc->getElementsByTagName('img'); 
$firstimage = $node->item(0)->getAttribute('src'); 

그럼 내가 볼 수있는 시험을한다.

<? 
function file_get_contents_curl($url) 
{ 
    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    $data = curl_exec($ch); 

    curl_close($ch); 

    return $data; 
} 

function getit($site) { 

    $parsing = file_get_contents_curl($site); 
    //parsing begins here: 
    $doc = new DOMDocument(); 
    @$doc->loadHTML($parsing); 

    $nodes = $doc->getElementsByTagName('title'); 
    $node = $doc->getElementsByTagName('img'); 
    $para = $doc->getElementsByTagName('p'); 
    //get and display what you need: 

    $title = $nodes->item(0)->nodeValue; 
    $firstimage = $node->item(0)->getAttribute('src'); 
    $firstparagraph = $para->item(0)->nodeValue; 

    $metas = $doc->getElementsByTagName('meta'); 

    for ($i = 0; $i < $metas->length; $i++) 
    { 
     $meta = $metas->item($i); 
     if($meta->getAttribute('property') == 'og:description') { 
      $description = $meta->getAttribute('content'); 
     } 
     elseif ($meta->getAttribute('name') == 'description') { 
      $description = $meta->getAttribute('content'); 
     } else { 
      $descrition = "<p>".implode(' ', array_slice(explode(' ', $firstparagraph), 0, 25))."</p>"; 
     } 
     if($meta->getAttribute('property') == 'og:image') { 
      $image = $meta->getAttribute('content'); 
     } 
    } 

    if ($image != '') { $image = $image; } else { $image = $firstimage; } 

    $str .= 'Title: '.$title.' <br/><br/>'; 
    $str .= 'Description: '.$description.' <br/><br/>'; 
    $str .= 'Image: <img src="'.$image.'"><br/><br/>'; 
    echo $str; 
} 

?> 
관련 문제