8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

simplexml_load_string のエラーハンドリングを一生懸命やる! [try{}cacheで取れないなんて、反則だ!]

Last updated at Posted at 2015-03-16
f:id:makoto1899:20150206143758j:plain

FavoritesFollows(f14s.pw) で、ハマっていた simplexml_load_string のエラーハンドリング。最終的に、取得使用としていたRSSが、UTF-16 だったりと散々な結果に。一応、はてな なので相談をして、とりあえず動くものが出来たので、ソースを晒しておきます。

function getXmlData($rss_url = NULL) {
    set_error_handler(function($errno, $errstr, $errfile, $errline) {  
        throw new Exception($errstr, $errno);  
    });  

    try {
        $search = array("\0", "\x01", "\x02", "\x03", "\x04", "\x05","\x06", "\x07", "\x08", "\x0b", "\x0c", "\x0e", "\x0f");

        $options = array(
            'http' => array(
            'method' => 'GET',
            'header' => 'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36',
            ),
        );
        $context = stream_context_create($options);
        $xml_context = file_get_contents($rss_url, false, $context);
        $xml_context = str_replace($search, '', $xml_context);  

        if (mb_detect_encoding($xml_context, 'UTF-8', true) === false) { 
            $xml_context = utf8_encode($xml_context); 
        }

        if (strpos($xml_context, '<?xml', 0) === false){
            echo "×:Error:". $rss_url . "\n";
            return false;
        }

        $xml = simplexml_load_string($xml_context);

        if ($xml === false) {
            echo "Failed loading XML\n";
            foreach(libxml_get_errors() as $error) {
                echo "\t", $error->message;
            }
            return false;
        }
        restore_error_handler();
    } catch (Exception $ex) {
        restore_error_handler();  
        echo "×:Exception". $ex . "\n";  
        echo "×:Error:". $rss_url . "\n";
        return false;
    }

    return $xml;
}

ネットぐるぐるしまくって、いろいろな対策を施したソースなので、大抵のXMLはエラーにならないと思います。自己責任でどうぞ。

8
5
1

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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?