我正在尝试显示外部网站标头中的编码(例如:UTF-8(并将其保存到我的JSON文件中。
它像这样显示所有内容:text/html; charset=UTF-8
但我不想显示超过必要的信息,我只想显示例如:UTF-8
有人可以告诉我解决它的好方法吗?
$jsonContents = file_get_contents('data/data.json');
$data_array = json_decode($jsonContents, true);
foreach ($data_array as $key => $value) {
$domain = "http://".$value['domain'];
$info = get_headers($domain, 1)["Content-Type"].split("=");
if (!empty($info)){
$data_array[$key]['encode'] = $info;
} else {
$data_array[$key]['encode'] = "It don't have Encode";
}
$json = json_encode($data_array);
file_put_contents('data/data.json', $json);
};
试试这个:
$info = get_headers($domain, 1)["Content-Type"]; // text/html; charset=UTF-8
$ex = explode('=', $info);
$encoding = end($ex);
echo $encoding;
这将输出 UTF-8
看这里 https://3v4l.org/NX4Pb
我认为你的php中有一些javascript。
更改此设置:
$info = get_headers($domain, 1)["Content-Type"].split("=");
对此:
$temp = explode('=', get_headers($domain, 1)["Content-Type"]) ;
// we use end($temp) here in case there is no '=' in your result
$info = $temp[end($temp)] ;
尝试使用$info = get_headers($domain, 1)["Content-Type"].split("charset=");
,因为可能有多个值具有=