Special characters and double quotes issue in PHP

2019-07-27 07:53发布

I have this kind of value in my db column,

Judge-Fürstová Mila "Ut enim ad minim veniam"

I use PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" to handle all my special characters,

class database_pdo
{
    # database handler
    protected $connection = null;

    # make a connection
    public function __construct($dsn,$username,$password)
    {
        try 
        {

            $this->connection = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

        }
        catch (PDOException $e) 
        {
            # call the get_error function
            $this->get_error($e);
        }
    }
    ...
    ...
    ...

 }

And when I try to print that value in my input field,

<input name="title" type="text" value="<?php echo $page->title;?>"/>

I only get Judge-Fürstová Mila in my input field.

If I use htmlentities to fix the double quotes issue,

<input name="title" type="text" value="<?php echo htmlentities($page->title);?>"/>

I get this in my input field,

Judge-Fürstová Mila "Ut enim ad minim veniam"

So, how can I fix this special characters and double quotes issue at once?

2条回答
戒情不戒烟
2楼-- · 2019-07-27 08:07

htmlentities() works with ISO-8869-1 encoding by default prior to PHP5.4

Try supplying encoding parameter to a function call:

<?php echo htmlentities($page->title, ENT_COMPAT | ENT_HTML401, 'UTF-8');?>

No way to bypass supplying second parameter, though, but ENT_COMPAT | ENT_HTML401 is the default anyway.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-27 08:08

Try using htmlspecialchars() instead of htmlentities().

查看更多
登录 后发表回答