<?php
header('Content-type:text/html;charset=UTF-8');
$url = 'http://www.xxx.com/text.xml';
$content = str_replace('gb2312', 'UTF-8', file_get_contents($url));
$content = iconv('GBK', 'UTF-8', $content);
// $content = utf8_encode($content);
// print_r($content);
// echo "<BR />************<BR />";
try{
$data = simplexml_load_string($content) or die('unable to load xml');
}catch(Excetion $e){
print_r($e->getMessage());
}
if(isset($data->Item)){
echo "ok<br />";
}else{
echo "error<br />";
}
echo "<BR />************<BR />";
print_r($data);
// $content = sxe($url);
// var_dump($content);
function sxe($url)
{
$xml = file_get_contents($url);
foreach ($http_response_header as $header)
{
if (preg_match('#^Content-Type: text/xml; charset=(.*)#i', $header, $m))
{
switch (strtolower($m[1]))
{
case 'utf-8':
// do nothing
break;
case 'iso-8859-1':
$xml = utf8_encode($xml);
break;
default:
$xml = iconv($m[1], 'utf-8', $xml);
}
break;
}
}
return simplexml_load_string($xml);
}
参考:
http://stackoverflow.com/questions/2899274/php-simplexml-why-does-simplexml-load-string-fail-to-parse-google-weather
http://bbs.csdn.net/topics/390070967#post-391437130
http://php.net/manual/zh/function.iconv.php
http://zhidao.baidu.com/question/157551132.html?fr=iks&word=php+%BD%E2%CE%F6xml%C2%D2%C2%EB&ie=gbk