リンクを介してウェブサイトのタイトルを取得します
-
30-09-2019 - |
質問
方法に注意してください グーグルニュース 各記事の底部には、抜粋の下部にソースがあります。
ガーディアン - ABCニュース - ロイター - ブルームバーグ
私はそれを真似しようとしています。
たとえば、URLを送信すると http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/
戻りたいです The Washington Times
PHPでこれはどのように可能ですか?
解決
私の答えは、ページのタイトルを使用するという@AI Wの答えに拡大しています。以下は、彼が言ったことを達成するためのコードです。
<?php
function get_title($url){
$str = file_get_contents($url);
if(strlen($str)>0){
$str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
return $title[1];
}
}
//Example:
echo get_title("http://www.washingtontimes.com/");
?>
出力
ワシントンタイムズ - 政治、壊れたニュース、米国、世界ニュース
ご覧のとおり、Googleが使用しているものではないため、URLのホスト名を取得して自分のリストにマッチすると信じるようになります。
http://www.washingtontimes.com/ =>ワシントンタイムズ
他のヒント
$doc = new DOMDocument();
@$doc->loadHTMLFile('http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/');
$xpath = new DOMXPath($doc);
echo $xpath->query('//title')->item(0)->nodeValue."\n";
出力:
債務委員会はテスト投票に不足しています - ワシントンタイムズ
明らかに、基本的なエラー処理も実装する必要があります。
URLの内容を取得し、のコンテンツの正規表現検索を行うことができます title
エレメント。
<?php
$urlContents = file_get_contents("http://example.com/");
preg_match("/<title>(.*)<\/title>/i", $urlContents, $matches);
print($matches[1] . "\n"); // "Example Web Page"
?>
または、正規表現を使用したくない場合(ドキュメントの上部に非常に近いものと一致するように) domdocumentオブジェクト:
<?php
$urlContents = file_get_contents("http://example.com/");
$dom = new DOMDocument();
@$dom->loadHTML($urlContents);
$title = $dom->getElementsByTagName('title');
print($title->item(0)->nodeValue . "\n"); // "Example Web Page"
?>
どの方法が一番好きかを決定するために、私はあなたに任せます。
Domain Home Pageからget_meta_tags()を使用すると、NYTは切り捨てられるかもしれないが有用なものを取り戻すことができます。
$b = "http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/" ;
$url = parse_url( $b ) ;
$tags = get_meta_tags( $url['scheme'].'://'.$url['host'] );
var_dump( $tags );
「ワシントンタイムズは、私たちの国の将来に影響を与える問題に関するニュースと解説を伝える」という説明が含まれています。
<?php
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
そして、これら2つをまとめる:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
$pattern = '/[<]title[>]([^<]*)[<][\/]titl/i';
preg_match($pattern, $output, $matches);
print_r($matches);
// close curl resource to free up system resources
curl_close($ch);
?>
ここにはPHPがないので、この例が機能することは約束できませんが、始めるのに役立つはずです。
あなたがこれにサードパーティのサービスを使用することをいとわない場合、私はちょうどそれを作成しました www.runway7.net/radar
タイトル、説明などを提供します。たとえば、試してみてください レーダーに関するあなたの例. (http://radar.runway7.net/?url=http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/)
または、使用することもできます シンプルなHTML DOMパーサー:
<?php
require_once('simple_html_dom.php');
$html = file_get_html('http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/');
echo $html->find('title', 0)->innertext . "<br>\n";
echo $html->find('div[class=entry-content]', 0)->innertext;
私はそれを処理するための関数を書きました:
function getURLTitle($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$charset = '';
if($contentType && preg_match('/\bcharset=(.+)\b/i', $contentType, $matches)){
$charset = $matches[1];
}
curl_close($ch);
if(strlen($content) > 0 && preg_match('/\<title\b.*\>(.*)\<\/title\>/i', $content, $matches)){
$title = $matches[1];
if(!$charset && preg_match_all('/\<meta\b.*\>/i', $content, $matches)){
//order:
//http header content-type
//meta http-equiv content-type
//meta charset
foreach($matches as $match){
$match = strtolower($match);
if(strpos($match, 'content-type') && preg_match('/\bcharset=(.+)\b/', $match, $ms)){
$charset = $ms[1];
break;
}
}
if(!$charset){
//meta charset=utf-8
//meta charset='utf-8'
foreach($matches as $match){
$match = strtolower($match);
if(preg_match('/\bcharset=([\'"])?(.+)\1?/', $match, $ms)){
$charset = $ms[1];
break;
}
}
}
}
return $charset ? iconv($charset, 'utf-8', $title) : $title;
}
return $url;
}
Webページのコンテンツを取得し、(最優先度から最低まで)ドキュメントチャーセットエンコードを取得しようとします。
- 「コンテンツタイプ」フィールドのHTTP「charset」パラメーター。
- 「http-equiv」が「content-type」に設定された「http-equiv」と「charset」の値が設定されたメタ宣言。
- CharSet属性は、外部リソースを指定する要素に設定します。
(見る http://www.w3.org/tr/html4/charset.html)
そして、使用します iconv
タイトルを変換します utf-8
エンコーディング。
リンクを介してウェブサイトのタイトルを取得し、タイトルをUTF-8文字エンコードに変換する:
https://gist.github.com/kisexu/b64bc6ab787f302ae838
function getTitle($url)
{
// get html via url
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$html = curl_exec($ch);
curl_close($ch);
// get title
preg_match('/(?<=<title>).+(?=<\/title>)/iU', $html, $match);
$title = empty($match[0]) ? 'Untitled' : $match[0];
$title = trim($title);
// convert title to utf-8 character encoding
if ($title != 'Untitled') {
preg_match('/(?<=charset\=).+(?=\")/iU', $html, $match);
if (!empty($match[0])) {
$charset = str_replace('"', '', $match[0]);
$charset = str_replace("'", '', $charset);
$charset = strtolower( trim($charset) );
if ($charset != 'utf-8') {
$title = iconv($charset, 'utf-8', $title);
}
}
}
return $title;
}
私はそれが必要でないときに正規表現を避けようとします、私は以下のCurlとDomdocumentでウェブサイトのタイトルを取得するための機能を作成しました。
function website_title($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// some websites like Facebook need a user agent to be set.
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36');
$html = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument;
@$dom->loadHTML($html);
$title = $dom->getElementsByTagName('title')->item('0')->nodeValue;
return $title;
}
echo website_title('https://www.facebook.com/');
以下を返します:Facebookへようこそ - ログイン、サインアップ、または詳細