LoginSignup
12
9

More than 3 years have passed since last update.

file_get_contentsがうまくいかない

Last updated at Posted at 2016-11-07

やろうとしたこと

file_get_content()を用いた某サービスのWebAPIからのデータ取得。

イメージ.php
$query = 'q=' . $searchText;
$opts = [
    'http' => [
        'method' => 'GET',
        'header' => 'user-agent:MyUserAgent'
    ]
];

$url = 'https://example.com/search?' . $query;
$result = file_get_contents($url, false, stream_context_create($opts));
... failed to open stream http request failed! HTTP/1.0 500 ...

すでにやっていること

  • カスタムUser-Agentを設定する(API側がUser-Agentで有効なクライアントかどうかを判定しているので。)

試したこと

  • アクセス先がhttpsなので、;extension=php_openssl.dllのコメントアウトを外す:x
  • allow_url_fopen=Onにする:x

それで結局どうしたか

結局今回の僕のケースでは、 http_build_query を利用することで解消しました。

今回僕が利用したAPIの場合、同じベースエンドポイントの他のAPIだとうまくデータが取得できたので、
接続方法に問題があると予想していたのですが、どうやらリクエストの仕方そのものに問題があったようです。

$query = http_build_query(['q' => $search_text]);
$opts = [
    'http' => [
        'method' => 'GET',
        'header' => 'user-agent:MyUserAgent'
    ]
];

$url = 'https://example.com/search?' . $query;
$result = file_get_contents($url, false, stream_context_create($opts));

結局 http_build_query を利用するとなんで動くかはわからなかったな、そういえば... :thinking:
@rryu さんのおっしゃる通り、$search_textの中身がいい感じにURLエンコードされたんだろうか...

2018.11.26 追記

ちなみに、http_build_queryには色々罠があるので、注意して使うべきです。
http_build_queryのセパレータの設定(arg_separator.output)がデフォルトだと &となっているケースがあり、それに気づかずリクエストして、400しか返ってこない。。。みたいなことがあります。(僕は2回やってます。反省)
この辺よしなにやってくれているフレームワークってやっぱり最強だなと思いました。(小並感)

参考↓
http://d.hatena.ne.jp/Fivestar/20100112/1263291544

12
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9