MNR
MNR

Reputation: 757

PHP: unreadable output characters

I am working on a page with PHP but the data (text) I stored in my database while I retrieve it it is showing unreadable characters as you can see from my online instance.

http://www.taleemulislam-radio.com/test.php

and my PHP code for that page is:

<?php
require_once "pdo.php";

try {
    $sql = "SELECT * FROM `content` ORDER BY `updated` DESC LIMIT 1";
    $result = $pdo->query($sql);
    $result = $result->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    die("Error: ".$e->getMessage());
}

header("Content-Type: text/html; charset=utf-8");
?>
<!DOCTYPE html>
<html lang="ps">
<head>
    <meta charset="utf-8">
    <title>تعليم الاسلام راډيو</title>
</head>
<body>
    <?=var_dump($result)?>
</body>
</html>

Sample: http://www.taleemulislam-radio.com/test.php

Upvotes: 0

Views: 973

Answers (1)

Rick James
Rick James

Reputation: 142518

The meta tag should be

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Set the charset attribute of the PDO dsn.

Declare you column(s) to be CHARACTER SET utf8. Provide SHOW CREATE TABLE content; for verification.

Let's check what is stored. Please do SELECT col, HEX(col) ...; to see if you get mostly D8xx and D9xx, such as:

D8AAD8B9D984D98AD98520D8A7D984

If your "unreadable characters" are something like

تعليم الاسلام راډيو

then you have the classic case of

  • The bytes you have in the client are correctly encoded in utf8.apostrophe.)
  • You connected with SET NAMES latin1 (or set_charset('latin1') or ...), probably by default. (It should have been utf8.)
  • The column in the table was declared CHARACTER SET latin1. (Or possibly it was inherited from the table/database.) (It should have been utf8.)

The fix for the data is a "2-step ALTER".

ALTER TABLE Tbl MODIFY COLUMN col VARBINARY(...) ...;
ALTER TABLE Tbl MODIFY COLUMN col VARCHAR(...) ... CHARACTER SET utf8 ...;

where the lengths are big enough and the other "..." have whatever else (NOT NULL, etc) was already on the column.

Upvotes: 1

Related Questions