【问题标题】:Why is file_get_contents() messing up GET data?为什么 file_get_contents() 会弄乱 GET 数据?
【发布时间】:2011-10-04 13:06:53
【问题描述】:

所以,据我所知,我的问题是 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 我得到一个正常的字符串,而不是一些乱七八糟的符号。

【问题讨论】:

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


    【解决方案1】:

    尝试使用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';
    

    【讨论】:

    • 大声笑!我很确定我已经尝试过了,但它没有用,但似乎我做错了什么。谢谢!我的问题现在解决了:)
    【解决方案2】:

    在 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" ) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      相关资源
      最近更新 更多