为什么file_get_contents()弄乱了GET数据?

时间:2011-10-04 13:06:53

标签: php encoding utf-8 file-get-contents

所以,据我所知,我的问题是file_get_contents()即使正在传递也不会发送正确的UTF-8 URL,因此服务器接收的$ _GET数据有点混乱。我的部分代码:

//receiving post data from html form "nacionālā opera"
$q = $_POST["q"];

if (!empty($q)) {
    $get_data = array( 
        'http' => array(
            'header'=> array("Content-Type: text/plain; charset=utf-8",
                             "User-agent: PHP bots;")   
        ) 
    );
    $stream_cont = stream_context_create($get_data);

    $search = str_replace(" ", "+", $q);
    $url = 'http://127.0.0.1/test.php?stotele='.$search.'&a=p.search&t=xml&day=1-5&l=lv';

    if (mb_detect_encoding($url) === 'UTF-8') {
        echo '$url encoding is ok...??';
    } else {
        echo 'URL encoding not UTF-8!';
        exit();
    }

    $rec_data = file_get_contents($url, false, $stream_cont);

以下是打印$ _GET数组时服务器获取的内容:

stotele => nacionÄ_lÄ_ opera // this should have been "nacionālā opera", but as u see it got distorted
a => p.search 
t => xml 
day => 1-5 
l => lv 

我希望你明白我想说的话。这件事让我疯狂,我无法解决它,如果有人给我提示会很好(是的,我的浏览器编码设置为UTF-8,也是表格发送UTF-8,如果我回应$ q或$ search或$ url我得到一个普通的字符串,而不是一些混乱的符号。

2 个答案:

答案 0 :(得分:2)

尝试使用urlencode

// instead of this:
// $search = str_replace(" ", "+", $q);
// use:
$search = urlencode($q);
$url = 'http://127.0.0.1/test.php?stotele='.$search.'&a=p.search&t=xml&day=1-5&l=lv';

答案 1 :(得分:0)

在php.net上看到它

if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")=="UTF-8" ) 

if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")==="UTF-8" )