Utf-8 Character Encoding Battles JSON_Encode()

UTF-8 character encoding battles json_encode()

// Create an empty array for the encoded resultset
$rows = array();

// Loop over the db resultset and put encoded values into $rows
while($row = mysql_fetch_assoc($result)) {
$rows[] = array_map('utf8_encode', $row);
}

// Output $rows
echo json_encode($rows);

json_encode not working on PDO fetched data

Here is what worked for me:
UTF-8 character encoding battles json_encode()

public function getCities($val) {
$sth = $this->db->prepare("SELECT id, name FROM cities WHERE w_id = :w_id");
$sth->execute(array(':w_id' => $val));

header("Content-type: application/json; charset=utf-8");

$rows = array();

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$rows[] = array_map('utf8_encode', $row);
}

echo json_encode($rows);
}

I found other answer here How to json_encode array with french accents? but keeps getting notices, illegal character found.

Mssql result json_encode not returning anything php pdo

I have found the best solution for my project in here

Using below code:

// Create an empty array for the encoded resultset

$rows = array();

// Loop over the db resultset and put encoded values into $rows

while($row = mysql_fetch_assoc($result)) {
$rows[] = array_map('utf8_encode', $row);
}

// Output $rows

echo json_encode($rows);

The answer was given my user Kemo

PHP Json Encode PDO::FETCH_ASSOC

json_encode is character encoding sensitive. It will fail if it can't handle the encoding. print_r is not. It will happily print out whatever you give it.

The utf8_encode fix will only work if the strings in your source data are encoded as ISO-8859-1. Assuming that's true it should work. Make sure you do it like this... https://stackoverflow.com/a/2790107/111755

JSON encoding using produces={application/json; charset=UTF-8} and ObjectMapper

Why don’t you just use
ResponseEntity

And return
new ResponseEntity<String>(“your message”, HttpStatus.OK);



Related Topics



Leave a reply



Submit