programing

외부 웹 사이트에서 제목 및 메타 태그 가져오기

bestprogram 2023. 7. 31. 21:32

외부 웹 사이트에서 제목 및 메타 태그 가져오기

나는 어떻게 그것을 얻는지 알아내고 싶습니다.

<title>A common title</title>
<meta name="keywords" content="Keywords blabla" />
<meta name="description" content="This is the description" />

어떤 순서로 배열되어 있더라도 PHP Simple HTML DOM Parser는 들어보았지만 별로 사용하고 싶지 않습니다.PHP Simple HTML DOM Parser를 사용하지 않는 솔루션이 가능합니까?

preg_match할 수 요? HTML이라면 할 수 없는 건가요?

cURL이 preg_match로 이와 같은 작업을 수행할 수 있습니까?

Facebook은 다음과 같은 작업을 수행하지만 다음을 사용하여 적절하게 사용됩니다.

<meta property="og:description" content="Description blabla" />

누군가 링크를 올리면 제목과 메타태그를 검색할 수 있도록 이런 것을 원합니다.메타태그가 없으면 무시되거나 사용자가 직접 설정할 수 있습니다.

다음과 같이 해야 합니다.

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);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$html = file_get_contents_curl("http://example.com/");

//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');

//get and display what you need:
$title = $nodes->item(0)->nodeValue;

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

for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
}

echo "Title: $title". '<br/><br/>';
echo "Description: $description". '<br/><br/>';
echo "Keywords: $keywords";
<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>

get_meta_tags제목을 제외한 모든 것을 도와줄 것입니다.제목을 얻으려면 정규식을 사용하십시오.

$url = 'http://some.url.com';
preg_match("/<title>(.+)<\/title>/siU", file_get_contents($url), $matches);
$title = $matches[1];

도움이 되길 바랍니다.

get_meta_tags제목과 함께 작동하지 않았습니다.

이름 특성이 다음과 같은 메타 태그만

<meta name="description" content="the description">

구문 분석됩니다.

PHP의 기본 함수: get_meta_tags()

http://php.net/manual/en/function.get-meta-tags.php

우리는 OG를 사용해야 하지 않나요?

선택한 답변은 좋지만 사이트를 리디렉션할 때(매우 일반적임!) 작동하지 않으며 새로운 산업 표준OG 태그를 반환하지 않습니다.여기 2018년에 조금 더 유용한 기능이 있습니다.OG 태그를 가져오려고 시도하고 검색할 수 없는 경우 메타 태그로 다시 이동합니다.

function getSiteOG( $url, $specificTags=0 ){
    $doc = new DOMDocument();
    @$doc->loadHTML(file_get_contents($url));
    $res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;

    foreach ($doc->getElementsByTagName('meta') as $m){
        $tag = $m->getAttribute('name') ?: $m->getAttribute('property');
        if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('og:','',$tag)] = $m->getAttribute('content');
    }
    return $specificTags? array_intersect_key( $res, array_flip($specificTags) ) : $res;
}

사용 방법:

/////////////
//SAMPLE USAGE:
print_r(getSiteOG("http://www.stackoverflow.com")); //note the incorrect url

/////////////
//OUTPUT:
Array
(
    [title] => Stack Overflow - Where Developers Learn, Share, & Build Careers
    [description] => Stack Overflow is the largest, most trusted online community for developers to learn, shareâ âtheir programming âknowledge, and build their careers.
    [type] => website
    [url] => https://stackoverflow.com/
    [site_name] => Stack Overflow
    [image] => https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded
)

안타깝게도 내장된 php 함수 get_meta_tags()에는 이름 매개 변수가 필요하며 트위터와 같은 특정 사이트는 속성 속성을 선호하여 이 매개 변수를 해제합니다.정규식 문서와 돔 문서를 혼합하여 사용하는 이 함수는 웹 페이지에서 메타태그의 키 배열을 반환합니다.이름 매개 변수를 확인한 다음 속성 매개 변수를 확인합니다.이것은 인스타그램, 핀터레스트 및 트위터에서 테스트되었습니다.

/**
 * Extract metatags from a webpage
 */
function extract_tags_from_url($url) {
  $tags = array();

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

  $contents = curl_exec($ch);
  curl_close($ch);

  if (empty($contents)) {
    return $tags;
  }

  if (preg_match_all('/<meta([^>]+)content="([^>]+)>/', $contents, $matches)) {
    $doc = new DOMDocument();
    $doc->loadHTML('<?xml encoding="utf-8" ?>' . implode($matches[0]));
    $tags = array();
    foreach($doc->getElementsByTagName('meta') as $metaTag) {
      if($metaTag->getAttribute('name') != "") {
        $tags[$metaTag->getAttribute('name')] = $metaTag->getAttribute('content');
      }
      elseif ($metaTag->getAttribute('property') != "") {
        $tags[$metaTag->getAttribute('property')] = $metaTag->getAttribute('content');
      }
    }
  }

  return $tags;
}

og를 검색하는 방법을 이해하는 간단한 기능: 태그, 제목 및 설명, 사용자가 직접 조정

function read_og_tags_as_json($url){


    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $HTML_DOCUMENT = curl_exec($ch);
    curl_close($ch);

    $doc = new DOMDocument();
    $doc->loadHTML($HTML_DOCUMENT);

    // fecth <title>
    $res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;

    // fetch og:tags
    foreach( $doc->getElementsByTagName('meta') as $m ){

          // if had property
          if( $m->getAttribute('property') ){

              $prop = $m->getAttribute('property');

              // here search only og:tags
              if( preg_match("/og:/i", $prop) ){

                  // get results on an array -> nice for templating
                  $res['og_tags'][] =
                  array( 'property' => $m->getAttribute('property'),
                          'content' => $m->getAttribute('content') );
              }

          }
          // end if had property

          // fetch <meta name="description" ... >
          if( $m->getAttribute('name') == 'description' ){

            $res['description'] = $m->getAttribute('content');

          }


    }
    // end foreach

    // render JSON
    echo json_encode($res, JSON_PRETTY_PRINT |
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

}

이 페이지로 돌아가기(더 많은 정보가 있을 수 있음):

{
    "title": "php - Getting title and meta tags from external website - Stack Overflow",
    "og_tags": [
        {
            "property": "og:type",
            "content": "website"
        },
        {
            "property": "og:url",
            "content": "https://stackoverflow.com/questions/3711357/getting-title-and-meta-tags-from-external-website"
        },
        {
            "property": "og:site_name",
            "content": "Stack Overflow"
        },
        {
            "property": "og:image",
            "content": "https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon@2.png?v=73d79a89bded"
        },
        {
            "property": "og:title",
            "content": "Getting title and meta tags from external website"
        },
        {
            "property": "og:description",
            "content": "I want to try figure out how to get the\n\n&lt;title&gt;A common title&lt;/title&gt;\n&lt;meta name=\"keywords\" content=\"Keywords blabla\" /&gt;\n&lt;meta name=\"description\" content=\"This is the descript..."
        }
    ]
}

당신의 최선의 방법은 DOM 파서를 사용하는 것입니다 - 그것은 그것을 하는 '올바른 방법'입니다.장기적으로 볼 때, 그것은 어떻게 하는지 배우는 데 걸리는 시간보다 더 많은 시간을 절약해 줄 것입니다.정규식을 사용하여 HTML을 구문 분석하는 것은 신뢰할 수 없고 특수한 경우를 용납할 수 없는 것으로 알려져 있습니다.

php를 통한 Apache Tika(명령줄 유틸리티)를 json용으로 -j와 함께 사용합니다.

http://tika.apache.org/

<?php
    shell_exec( 'java -jar tika-app-1.4.jar -j http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying' );
?>

다음은 임의의 보호 문서에서 출력된 샘플입니다.

{
   "Content-Encoding":"UTF-8",
   "Content-Length":205599,
   "Content-Type":"text/html; charset\u003dUTF-8",
   "DC.date.issued":"2013-07-21",
   "X-UA-Compatible":"IE\u003dEdge,chrome\u003d1",
   "application-name":"The Guardian",
   "article:author":"http://www.guardian.co.uk/profile/nicholaswatt",
   "article:modified_time":"2013-07-21T22:42:21+01:00",
   "article:published_time":"2013-07-21T22:00:03+01:00",
   "article:section":"Politics",
   "article:tag":[
      "Lynton Crosby",
      "Health policy",
      "NHS",
      "Health",
      "Healthcare industry",
      "Society",
      "Public services policy",
      "Lobbying",
      "Conservatives",
      "David Cameron",
      "Politics",
      "UK news",
      "Business"
   ],
   "content-id":"/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "dc:title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
   "description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
   "fb:app_id":180444840287,
   "keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
   "msapplication-TileColor":"#004983",
   "msapplication-TileImage":"http://static.guim.co.uk/static/a314d63c616d4a06f5ec28ab4fa878a11a692a2a/common/images/favicons/windows_tile_144_b.png",
   "news_keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
   "og:description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
   "og:image":"https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pixies/2013/7/21/1374433351329/Lynton-Crosby-008.jpg",
   "og:site_name":"the Guardian",
   "og:title":"Tory strategist Lynton Crosby in new lobbying row",
   "og:type":"article",
   "og:url":"http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "resourceName":"tory-strategist-lynton-crosby-lobbying",
   "title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
   "twitter:app:id:googleplay":"com.guardian",
   "twitter:app:id:iphone":409128287,
   "twitter:app:name:googleplay":"The Guardian",
   "twitter:app:name:iphone":"The Guardian",
   "twitter:app:url:googleplay":"guardian://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "twitter:card":"summary_large_image",
   "twitter:site":"@guardian"
}

제 솔루션(크로노클리 & 샤미토마의 게시물 일부에서 수정됨)은 어디서든 전화를 걸어 JSON 반품을 받을 수 있습니다.모든 콘텐츠에 쉽게 구문 분석할 수 있습니다.

<?php
header('Content-type: application/json; charset=UTF-8');

if (!empty($_GET['url']))
{
    file_get_contents_curl($_GET['url']);
}
else
{
    echo "No Valid URL Provided.";
}


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);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    echo json_encode(getSiteOG($data), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

function getSiteOG( $OGdata){
    $doc = new DOMDocument();
    @$doc->loadHTML($OGdata);
    $res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;

    foreach ($doc->getElementsByTagName('meta') as $m){
        $tag = $m->getAttribute('name') ?: $m->getAttribute('property');
        if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('og:','',$tag)] = utf8_decode($m->getAttribute('content'));

    }

    return $res;
}
?>

url, php 함수에서 메타 태그 가져오기 예제:

function get_meta_tags ($url){
         $html = load_content ($url,false,"");
         print_r ($html);
         preg_match_all ("/<title>(.*)<\/title>/", $html["content"], $title);
         preg_match_all ("/<meta name=\"description\" content=\"(.*)\"\/>/i", $html["content"], $description);
         preg_match_all ("/<meta name=\"keywords\" content=\"(.*)\"\/>/i", $html["content"], $keywords);
         $res["content"] = @array("title" => $title[1][0], "descritpion" => $description[1][0], "keywords" =>  $keywords[1][0]);
         $res["msg"] = $html["msg"];
         return $res;
}

예:

print_r (get_meta_tags ("bing.com") );

메타 태그 가져오기 php

간편함과 php의 내장 기능.

http://php.net/manual/en/function.get-meta-tags.php

만약 당신이 PHP로 작업하고 있다면, pear.php.net 에서 Pear 패키지를 확인하고 당신에게 유용한 것을 찾으세요.RSS 패키지를 효과적으로 사용했으며 예제를 통해 RSS 패키지가 코드를 구현하는 방법을 추적할 수 있다면 많은 시간이 많이 절약됩니다.

구체적으로 색스 3을 살펴보고 필요에 맞게 작동할지 확인하십시오.색스 3은 더 이상 업데이트되지 않지만 충분할 수 있습니다.

이미 언급했듯이, 이것은 문제를 처리할 수 있습니다.

$url='http://stackoverflow.com/questions/3711357/get-title-and-meta-tags-of-external-site/4640613';
$meta=get_meta_tags($url);
echo $title=$meta['title'];

//php - Get Title and Meta Tags of External site - Stack Overflow
<?php 

// ------------------------------------------------------ 

function curl_get_contents($url) {

    $timeout = 5; 
    $useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0'; 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 

    return $data; 
}

// ------------------------------------------------------ 

function fetch_meta_tags($url) { 

    $html = curl_get_contents($url); 
    $mdata = array(); 

    $doc = new DOMDocument();
    $doc->loadHTML($html);

    $titlenode = $doc->getElementsByTagName('title'); 
    $title = $titlenode->item(0)->nodeValue;

    $metanodes = $doc->getElementsByTagName('meta'); 
    foreach($metanodes as $node) { 
    $key = $node->getAttribute('name'); 
    $val = $node->getAttribute('content'); 
    if (!empty($key)) { $mdata[$key] = $val; } 
    }

    $res = array($url, $title, $mdata); 

    return $res;
}

// ------------------------------------------------------ 

?>

저는 이 작은 작곡가 패키지를 최고의 답을 바탕으로 만들었습니다: https://github.com/diversen/get-meta-tags

composer require diversen/get-meta-tags

그리고 나서:

use diversen\meta;

$m = new meta();

// Simple usage, get's title, description, and keywords by default
$ary = $m->getMeta('https://github.com/diversen/get-meta-tags');
print_r($ary);

// With more params
$ary = $m->getMeta('https://github.com/diversen/get-meta-tags', array ('description' ,'keywords'), $timeout = 10);
print_r($ary);

최고 답변으로 CURL과 DOMDocument가 필요하며, 기본적으로 구축되지만, 컬 타임아웃(및 모든 종류의 메타태그 가져오기)을 설정할 수 있는 옵션이 있습니다.

오늘날 대부분의 사이트는 사이트 또는 특정 기사 페이지에 대한 정보를 제공하는 메타 태그를 사이트에 추가합니다.뉴스 또는 블로그 사이트 등.

OpenGraph, Schema와 같은 필수 메타데이터 ac를 제공하는 Meta API를 만들었습니다.조직 등

확인해 보세요 - https://api.sakiv.com/docs

저는 이것을 다른 방식으로 작동하게 했고 공유하려고 생각했습니다.다른 사람들보다 코드가 적었고 여기서 찾았습니다.특정 페이지 대신 당신이 있는 페이지 메타를 로드할 수 있도록 몇 가지를 추가했습니다.저는 이것이 기본 페이지 제목과 설명을 og 태그에 자동으로 복사하기를 원했습니다.

하지만 어떤 이유에서인지, 제가 어떤 방법을 시도하든(다른 스크립트), 페이지는 온라인에서 매우 느리게 로드되지만 wamp에서는 즉시 로드됩니다. 왜 그런지는 모르겠지만 사이트가 넓지 않아서 아마 스위치 케이스로 갈 것 같습니다.

<?php
$url = 'http://sitename.com'.$_SERVER['REQUEST_URI'];
$fp = fopen($url, 'r');

$content = "";

while(!feof($fp)) {
    $buffer = trim(fgets($fp, 4096));
    $content .= $buffer;
}

$start = '<title>';
$end = '<\/title>';

preg_match("/$start(.*)$end/s", $content, $match);
$title = $match[1];

$metatagarray = get_meta_tags($url);
$description = $metatagarray["description"];

echo "<div><strong>Title:</strong> $title</div>";
echo "<div><strong>Description:</strong> $description</div>";
?>

그리고 HTML 헤더에.

<meta property="og:title" content="<?php echo $title; ?>" />
<meta property="og:description" content="<?php echo $description; ?>" />

메타 태그(또는 html 소스에서 지정된 태그)를 가져오기 위해 위의 @shamittomar에서 답변이 개선되었습니다.

더 개선될 수 있습니다...php의 기본 get_http_http와 다른 점은 유니코드 문자열이 있을 때도 작동한다는 것입니다.

function getMetaTags($html, $name = null)
{
    $doc = new DOMDocument();
    try {
        @$doc->loadHTML($html);
    } catch (Exception $e) {

    }

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

    $data = [];
    for ($i = 0; $i < $metas->length; $i++)
    {
        $meta = $metas->item($i);

        if (!empty($meta->getAttribute('name'))) {
            // will ignore repeating meta tags !!
            $data[$meta->getAttribute('name')] = $meta->getAttribute('content');
        }
    }

    if (!empty($name)) {
        return !empty($data[$name]) ? $data[$name] : false;
    }

    return $data;
}

페이지 메타 상세 정보를 얻을 수 있는 PHP 단순 DOM HTML Class 2줄 코드입니다.

$html = file_get_html($link);
$meat_description = $html->find('head meta[name=description]', 0)->content;
$meat_keywords = $html->find('head meta[name=keywords]', 0)->content;

만약 당신이 그것을 간결하게 하고, 나쁜 HTML/잘못된 URL을 다루기를 원한다면, 이것이 제가 사용하는 것입니다.

@if(substr(get_headers('https://www.google.com/')[0], 9, 3) == 200)
{
    @$title = preg_replace('/.*<title>(.*)<\/title>.*|.*/si', '\1',file_get_contents('https://www.google.com/'),1);
    @$desc = get_meta_tags('https://www.google.com/')['description']??'';
}

언급URL : https://stackoverflow.com/questions/3711357/getting-title-and-meta-tags-from-external-website