という話

技術ブログにしたい

日本語ドメインからfile_get_contentsを使ってHTMLを取得する

file_get_contentsって日本語ドメインに対応してないので、

$url = 'http://日本語.jp/';
$html = file_get_contents($url);
echo $html;

とかやろうとすると

PHP Warning:  file_get_contents(http://日本語.jp/): failed to open stream: php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in nihongo_domain.php on line 2

とか出て怒られます。

punycode

日本語ドメインってpunycodeという、普通のURLと同じような半角英数で出来たURLに変換されるようです。

日本語.jpだと
http://xn--wgv71a119e.jp/
というURLに変換されます。

このURLならfile_get_contentsでも取得できそうです。

日本語ドメインpunycodeに変換する

PHP標準ライブラリでは変換出来ないのでPEARのライブラリを使います。

sudo pear channel-update pear.php.net
sudo pear install Net_IDNA2-0.1.1

PHPで日本語ドメインを扱う方法(Punycode変換)
ここを参考にしてやってたんですが、

Non-static method NET_IDNA2::getInstance() should not be called statically.

ってエラーが出たのでちょっと変えてこうします

require_once 'Net/IDNA2.php';

$idna = new Net_IDNA2();
$idna_instance = $idna->getInstance();

$url = 'http://日本語.jp/';
$encoded_url = $idna_instance->encode($url);

$html = file_get_contents($url);
echo $html;

これで日本語ドメインpunycode変換してfile_get_contentsでhtmlを取得できます