simplexml_load_fileにtimeoutを利用したい場合の代替方法

simplexml_load_fileは便利なんですが、細かいオプションの設定などができなくて苦労する事があります。


今回はある程度レスポンスが遅い事が予測されるapiを利用していたのですが、たまに結果がそのままロストして帰ってこない事がありました。
しかしprocessはresponseを待ち続け、結局processがずっと走り続けちゃいました。

 69             $xml_data = simplexml_load_string($api_url);
 70             if ($xml_data && count($xml_data->xpath('fault')) == 0) {
 71                 //処理

curlとsimplexml_load_stringの併用

simplexml_load_fileの利用をあきらめ、curlとの併用を試みます。

 63             // timeoutを設定するために、curlを利用
 64             $ch = curl_init($api_url);
 65             curl_setopt($ch, CURLOPT_TIMEOUT, 300);
 66             curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
 67             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 戻り値を文字列で
 68             $xml_raw = curl_exec($ch);
 69             $xml_data = simplexml_load_string($xml_raw);
 70             if ($xml_data && count($xml_data->xpath('fault')) == 0) {
 71                 // 処理

curlに限らず、HTTP/Requestなどでもそうですが、connection用のtimeoutと、read用のtimeoutがあるのでご注意を。
特に理由がなければ、両方設定しておけば良いかと。


CURLOPT_RETURNTRANSFER を設定しないと、curl_execの戻り値が true になってしまいます。
文字列を返してもらって、simplexml_load_stringでパースしましょう。

stream_set_timeout

stream_set_timeoutを利用する方法もあるようです。
Re: [PHP] simpleXML - simplexml_load_file() timeout? [Resolved]


stream_set_timeoutのほうは動作確認してませんが、きっと動くんじゃないかと、淡い期待だけ抱いてます。