替换非破坏空间PHP

时间:2013-11-11 02:07:49

标签: php mysql json character-encoding

* json_encode返回NULL?不是答案。使用json_encode时仍然会收到NULL。*

我是PHP的新手,所以如果您可以使用固定代码编辑该部分,我会很感激。

这是我的问题:

当“introtext”下的文章包含非断行时,它返回NULL。没有非破坏空间的文章显示得很好。

这是我的问题:

如果“introtext”下的文章包含不间断的空间,我怎样才能正确显示这些文章。

以下是代码:

$connection = mysqli_connect($host, $user, $pass);

//Check to see if we can connect to the server
if(!$connection)
{
    die("Database server connection failed.");  

}else{

    //Attempt to select the database
    $dbconnect = mysqli_select_db($connection, $db);

    //Check to see if we could select the database
    if(!$dbconnect)
    {
        die("Unable to connect to the specified database!");

        }else{

        $catID = $_GET['catid'];
        $id = $_GET['id'];
        $rtn = $_GET['rtn'];        

        if($id!=""){
            $query = "SELECT * FROM tcp_content WHERE id=" . $id . "";
        }else{
            $query = "SELECT * FROM tcp_content WHERE catid=" . $catID . " ORDER BY publish_up DESC LIMIT " . $rtn . "";
        }

        $resultset = mysqli_query($connection,$query);
        $records = array();


        //Loop through all records and add them to array
        while($r = mysqli_fetch_assoc($resultset))
        {
            $r['introtext'] =  print_r($r['introtext'],true);
            $records[] = $r;        
        }

        //Output the data as JSON
        echo json_encode($records);
    }


}


?>

这里有两个链接:

This link contains the non breaking space, so you'll notice introtext returns NULL

This link does NOT contain the non breaking space, so you'll notice the article shows

2 个答案:

答案 0 :(得分:0)

我找到了这个链接json_encode problem

见第二个答案。 Charles建议使用iconv()删除URL编码的不间断空格。

答案 1 :(得分:0)

我终于明白了并让它发挥作用

            $r['introtext'] =  utf8_encode($r['introtext']);

            $r['introtext'] =  str_replace(chr(194).chr(160),' ',$r['introtext']);
            $r['introtext'] =  str_replace(chr(194).chr(147),'"',$r['introtext']);
            $r['introtext'] =  str_replace(chr(194).chr(148),'"',$r['introtext']);
            $r['introtext'] =  str_replace(chr(194).chr(146),"'",$r['introtext']);
            $r['introtext'] =  str_replace(chr(194).chr(145),"'",$r['introtext']);

            $r['introtext'] =   htmlentities($r['introtext'], ENT_QUOTES | ENT_IGNORE, "UTF-8");
            $records = $r;