目次
【PHP】ユーザエージェントの設定(file_get_contents,get_headers,curl)
PHPでスクレイピングを実施していこうと思ったら、
よく使うのがこの関数たち。
・file_get_contents
・get_headers
・curl
ただ、ユーザエージェントを設定できないと
スマホページのスクレイピングができないことがあったりなかったり。
というわけで、上の3つの関数について、
それぞれユーザエージェントの設定方法をご紹介します。
file_get_contents
1 2 3 4 5 6 7 8 9 10 |
$options = array( 'http' => array( 'method' => "GET", 'header' => "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_0_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13A404 Safari/601.1\n", ), ); $context = stream_context_create($options); $url = 'http://macbeese.com/'; $contents = file_get_contents($url, false, $context); |
stream_context_create()で色々とオプションを追加できます。
get_headers
1 2 3 4 5 6 7 8 9 10 11 |
$default_opts = array( 'http' => array( 'method'=>"GET", 'header'=>"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_0_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13A404 Safari/601.1\n", ) ); stream_context_get_default($default_opts); $url = 'http://macbeese.com/'; $headers = get_headers($url); |
stream_context_get_default()でデフォルトの設定をしておくことで、
get_headers()にも反映されます。
curl
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$url = 'http://macbeese.com/'; $user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_0_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13A404 Safari/601.1"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); // リダイレクトの際にヘッダのRefererを自動的に追加させる curl_setopt($curl, CURLOPT_TIMEOUT, 10); // タイムアウト(秒) $result = curl_exec($curl); curl_close($curl); |
CURLOPT_USERAGENTで設定できます。
以上です!
割りと簡単に設定できます!
ユーザエージェントの設定って結構必要になるのに
PHPマニュアルには、わかりやすく載っていない。
2016年最大のなぞ・・・・
The following two tabs change content below.
デミ
Z or R Twice
で検索すると…
最新記事 by デミ (全て見る)
- 【20分で完了】MacにDocker for Macのインストール - 2017/02/02
- 【2017年版】Web接客ツール9社を比較してみた - 2017/01/26
- 【昼休み中に完了!】Macで最新Ruby、Railsのインストールから画面表示まで - 2017/01/19