user3853938
user3853938

Reputation:

How do I print special characters in JSON?

while ($row = $results->fetch_assoc()) {
    $rows[] = array(
                    'id' => $row['id'],
                    'shipDataLastLocaltion' => $row['SDLLP']
                   );
}

print '{"data": ';
echo json_encode($rows, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
print "}";
$this->response('', 200);

Data in the table:

 $row['SDLLP'] //-> "Istanbul’Beşiktaş"point:3""

Error screen:

SyntaxError: JSON.parse: unexpected character at line 1 column 10 of the JSON data

The reason for the error:

These characters are in the table " and

JSON does not work because of these characters - I used this function for this, but it did not work.

I tried this for the solution htmlspecialchars and other methods I found on the internet but all method did not work.

What could be the solution to this?

Upvotes: 0

Views: 744

Answers (3)

user3853938
user3853938

Reputation:

Is just enough

// Change character set to utf8
mysqli_set_charset($con,"utf8");

or

$mysqli->set_charset("utf8");

Upvotes: 0

Amaid Niazi
Amaid Niazi

Reputation: 162

While printing just use backslash \ before each and every special character. It will start accepting those characters as json simple string for example:

\" quotation
\\ backslash 

Pick the data using your server side language and add backslash \ before each and every special character and then make the json and return it to the client side.

Thanks.

Upvotes: 1

Bora Erbasoglu
Bora Erbasoglu

Reputation: 107

These unwanted characters coming from Database i think. First of all you need to set collation Mysql collation

If still you have a problem you have to use iconv function to change encoding of these words.

Upvotes: 0

Related Questions