[英]PHP Curl UTF-8 Charset
我有一個 php 腳本,它調用另一個網頁並寫入頁面的所有 html,一切正常,但是存在字符集問題。 我的 php 文件編碼是 utf-8 並且所有其他 php 文件都可以正常工作(這意味着服務器沒有問題)。 該代碼中缺少什么,所有西班牙語字母看起來都很奇怪。 附注。 當我將這些奇怪的字符原始版本寫入php時,它們看起來都很准確。
header("Content-Type: text/html; charset=utf-8");
function file_get_contents_curl($url)
{
$ch=curl_init();
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
$data=curl_exec($ch);
curl_close($ch);
return $data;
}
$html=file_get_contents_curl($_GET["u"]);
$doc=new DOMDocument();
@$doc->loadHTML($html);
簡單:當您使用 curl 時,它將字符串編碼為utf-8
您只需要對其進行解碼即可。
Description
string utf8_decode ( string $data )
此函數將假定為UTF-8
編碼的 data 解碼為ISO-8859-1
。
你可以使用這個標題
header('Content-type: text/html; charset=UTF-8');
並在解碼字符串后
$page = utf8_decode(curl_exec($ch));
它對我有用
$output = curl_exec($ch);
$result = iconv("Windows-1251", "UTF-8", $output);
function page_title($val){
include(dirname(__FILE__).'/simple_html_dom.php');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$val);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0');
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$return = curl_exec($ch);
$encot = false;
$charset = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
$html = str_get_html('"'.$return.'"');
if(strpos($charset,'charset=') !== false) {
$c = str_replace("text/html; charset=","",$charset);
$encot = true;
}
else {
$lookat=$html->find('meta[http-equiv=Content-Type]',0);
$chrst = $lookat->content;
preg_match('/charset=(.+)/', $chrst, $found);
$p = trim($found[1]);
if(!empty($p) && $p != "")
{
$c = $p;
$encot = true;
}
}
$title = $html->find('title')[0]->innertext;
if($encot == true && $c != 'utf-8' && $c != 'UTF-8') $title = mb_convert_encoding($title,'UTF-8',$c);
return $title;
}
我正在通過 cURL 和mb_detect_encoding(curl_exec($ch));
獲取一個 windows-1252 編碼的文件mb_detect_encoding(curl_exec($ch));
返回 UTF-8。 試過utf8_encode(curl_exec($ch));
並且字符是正確的。
我之前嘗試過的最好方法是使用urlencode()
。 請記住,不要在整個 url 中使用它; 相反,僅將其用於所需的部分。 例如,一個請求有兩個 'text-fa' 和 'text-en' 字段,它們分別包含一個波斯語和一個英語文本,您可能只需要對波斯語文本進行編碼,而不是對英語文本進行編碼。
但是,如果必須編碼的字符范圍更有限,則有更好的方法。 其中一種方法是使用CURLOPT_ENCODING
,將其傳遞給curl_setopt()
:
curl_setopt($ch, CURLOPT_ENCODING, "");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.