Created
February 6, 2015 05:36
-
-
Save hamaguchi/cb6acf435ddfe469d2a7 to your computer and use it in GitHub Desktop.
PHP simplexml_load_string のエラーハンドリングを一生懸命やる!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment