レンタルサーバーによっては、allow_url_fopen=off、あるいは、file_get_contents=offの場合があり、RSSパースするのに必須なsimplexml_load_fileがそのままでは使えないことがある。

その場合、.htaccessを使ったり、プログラム冒頭で、ini_set関数を使えるか、先ず試してみる。

.htaccess

php_flag allow_url_fopen On
(参考、On/Off以外の値の変更の場合は、以下のようにかく)
php_value default_charset UTF-8
php_value mbstring.input_encoding pass
php_value mbstring.internal_encoding UTF-8
php_value mbstring.output_encoding pass
php_value mbstring.language Japanese
php_value mbstring.substitute_character none

ini_set関数

<?php
echo ini_get('allow_url_fopen');
if (!ini_get('allow_url_fopen')) {
    ini_set('allow_url_fopen', 1);
}
echo ini_get('allow_url_fopen');
?>

上の設定で駄目な場合、cURLを使う。

cURL

PHPで外部のリソースを取得するのに大変便利なfile_get_contents関数だが、cURLの環境があるなら利用したほうがパフォーマンスよい。

パフォーマンスの差

具体的にどれくらいパフォーマンスが変わるのかというと…
モバイル回線のノートでYahoo!のトップページを取得してざっくり計測したところ、

file_get_contents : 4秒前後
cURL : 2秒前後

具体的には、以下のようなコーディング

simplexml_load_file

//allow_url_fopen=onの場合
$rss = @simplexml_load_file($a); 
//allow_url_fopen=offの場合
$ch = curl_init($a);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml_raw = curl_exec($ch);
$rss = @simplexml_load_string($xml_raw);

file_get_contents

//file_get_contentsがきく場合
$buf = @file_get_contents($url); 
//file_get_contentsがきかない場合
$ch2 = curl_init($url);
curl_setopt($ch2, CURLOPT_HEADER, false);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
$buf = curl_exec($ch2);

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です