我创建了一个function
,可以从给定的网址中抓取title
并返回json
。该函数由ajax
调用。一切正常,但当任何标题包含ü或任何相关字符时,它返回null
。我在网络选项卡中回显字符串,它显示 而不是字符ü。
我尝试过从互联网上获得的解决方案,比如使用JSON Constant
,solution[1],solution[2],solution[3]和许多
在我尝试htmlentities
但它返回空字符串
代码:
$value = array();
$val['title'] = get_title("URL");
$val['link'] = $line;
array_push($value, $val);
function get_title($url)
{
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$query = curl_exec($curl_handle);
curl_close($curl_handle);
$normalizeChars = array(
'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A',
'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I',
'Ï'=>'I', 'Ñ'=>'N', 'Ń'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U',
'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a',
'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i',
'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ń'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u',
'ú'=>'u', 'û'=>'u', 'ü'=>'u', 'ü' => 'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f',
'ă'=>'a', 'î'=>'i', 'â'=>'a', 'ș'=>'s', 'ț'=>'t', 'Ă'=>'A', 'Î'=>'I', 'Â'=>'A', 'Ș'=>'S', 'Ț'=>'T', '�' => 'u',
);
$query = trim(preg_replace('/\s+/', ' ', $query)); // supports line breaks inside <title>
preg_match("/\<title\>(.*)\<\/title\>/", $query, $title); // ignore case
$search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø,Ø,Å,Á,À,Â,Ä,È,É,Ê,Ë,Í,Î,Ï,Ì,Ò,Ó,Ô,Ö,Ú,Ù,Û,Ü,Ÿ,Ç,Æ,Œ,�");
$replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o,O,A,A,A,A,A,E,E,E,E,I,I,I,I,O,O,O,O,U,U,U,U,Y,C,AE,OE,u");
//$title[1] = strtr($title[1], $normalizeChars); //Tried strtr function not work
//echo str_replace($search, $replace, $title[1]); // tried replace function not work
//echo $title[1];
//$title[1] = htmlentities($title[1]); //works but $title[1] is null
if (strpos($url, '/') !== false) {
$url1 = explode('/', $url1);
$res = $url1[0] . ' | ' . $title[1];
} else {
$res = $url1 . ' | ' . $title[1];
}
$res = substr($res, 0, 99);
return $res;
}
catch(Exception $e) { echo $e; }
}
echo json_encode($value);
答案 0 :(得分:1)
尝试使用JSON_UNESCAPED_UNICODE(仅适用于PHP&gt; = 5.4.0):
json_encode($value, JSON_UNESCAPED_UNICODE);