2010-09-14 14 views
46

quiero probar averiguar cómo obtener elObtención de título y meta etiquetas de sitio web externo

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

A pesar de que si se dispone en cualquier orden, he oído de la Simple PHP HTML DOM Analizador pero realmente no quiero usarlo. ¿Es posible una solución, excepto el uso del Analizador PHP PHP HTML simple?

preg_match no podrá hacerlo si no es HTML válido?

¿Puede cURL hacer algo como esto con preg_match?

Facebook hace algo como esto, pero lo use adecuadamente mediante el uso de:

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

Quiero algo como esto por lo que es posible cuando alguien publica un enlace, debe recuperar el título y las etiquetas meta. Si no hay metaetiquetas, entonces se ignora o el usuario puede establecerlo por sí mismo (pero lo haré más adelante).

Respuesta

140

Esta es la manera que debe ser:

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"; 
+3

esto no funciona para todos los sitios web. por ejemplo: http://www.baidu.com – Prakash

+2

Dos años después y todavía funciona sin problemas, cambié los atributos para obtener las etiquetas 'og:' relacionadas con OpenGraph y funciona perfectamente bien – Yaroslav

+0

¡Impresionante! Gracias Shamittomar. Agregue 'strtolower' alrededor de' $ meta-> getAttribute() '!! A veces tienen un capital al frente – JoeRocc

4

Su mejor opción es morder la bala usando el analizador DOM - es la "manera correcta" de hacerlo. A largo plazo, le ahorrará más tiempo de lo necesario para aprender cómo hacerlo. Se sabe que analizar HTML con Regex es poco fiable e intolerante con casos especiales.

+0

1, con la particularidad de que si sólo se utiliza el extensión DOM incorporada en lugar del Analizador de DOM simple HTML, probablemente sea un _lot_ más rápido, y no desordene el código con una biblioteca de terceros (aunque, agrega un requisito a su entorno de servidor, es decir, DOM habilitado, que es por defecto). – Wrikken

0

Si está trabajando con PHP, echa un vistazo a los paquetes de pera en pear.php.net y ver si encuentras algo útil para usted. Utilicé los paquetes RSS de manera efectiva y ahorró mucho tiempo, siempre que pueda seguir cómo implementan su código a través de sus ejemplos.

Mire específicamente Sax 3 y vea si funciona para sus necesidades. Sax 3 ya no se actualiza, pero podría ser suficiente.

6

get_meta_tags te ayudarán con todo menos el título. Para obtener el título solo usa una expresión regular.

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

Espero que ayude.

31
<?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 
?> 
+1

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

+3

esto no proporciona el título de la página aunque –

+0

^porque es una función relacionada con la metaetiqueta, ¿cómo diablos va a regresar? algo, no le preocupa. –

0

Como ya se dijo, esto puede manejar el problema:

$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 
4

get_meta_tags no funcionó con el título.

Sólo las etiquetas meta con atributos como nombre

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

será analizada.

1

Get meta tags de URL, la función php ejemplo:

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

Ejemplo:

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

Get Meta Tags php

+1

No olvide que los atributos 'name' y' content' pueden estar en orden diferente. – MacMac

2

Utilizamos Apache Tika a través de PHP (utilidad de línea de comandos) con -j para JSON:

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'); 
?> 

Ésta es una muestra de salida de forma aleatoria artículo guardián:

{ 
    "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" 
} 
+0

hosting compartido o básico no es compatible con Java en sus servidores :) –

-1

Aquí está PHP simple DOM HTML Clase dos líneas de código para obtener detalles de la página META.

$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; 
1
<?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; 
} 

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

?> 
2

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

<?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 
?> 
2

Por desgracia, las construidas en get_meta_tags php function() requiere el parámetro de nombre, y ciertos sitios, como Twitter Deja que fuera a favor del atributo de la propiedad. Esta función, al usar una combinación de regex y documento dom, devolverá una matriz con clave de metaetiquetas desde una página web. Comprueba el parámetro de nombre, luego el parámetro de propiedad. Esto ha sido probado en instragram, pinterest y twitter.

/** 
* 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; 
} 
0

hice este pequeño paquete compositor basado en la respuesta superior: https://github.com/diversen/get-meta-tags

composer require diversen/get-meta-tags 

Y luego:

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

Requiere Curl y DOMDocument, ya que la respuesta más común - y es construido en el camino, pero tiene la opción de configurar el tiempo de espera de curl (y para obtener todo tipo de metaetiquetas).

+1

BTW: Se considera buena (y común) la práctica de nombrar las clases comenzando con letra mayúscula, por lo que 'clase meta ...' debe ser' clase Meta ... .'. Es posible que desee seguir un patrón ampliamente adoptado aquí también –

+0

@MarcinOrlowski Tiene razón. La mejor práctica y todo eso. Mal hábito .) – dennis

0

Hoy en día, la mayoría de los sitios añaden metaetiquetas a sus sitios que proporcionan información sobre su sitio o cualquier página de artículo en particular. Tales como sitios de noticias o blogs.

He creado una API Meta que le da necesario CA metadatos como OpenGraph, Schema.Org, etc.

Compruébelo usted mismo - https://api.sakiv.com/docs

Cuestiones relacionadas