如何确保从MySQL检索的数据是PHP中的json_encode的UTF8?

时间:2016-10-24 09:59:49

标签: php json mysqli

我在PHP,MySQLi和json_encode的帮助下将SQL表行转换为JSON。

我目前的代码方法是 -

<?php
error_reporting(0);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if(isset($_GET['from'])) {
  $from = $_GET['from'] - 1;
} else {
  $from = 0;
}

if(isset($_GET['count'])) {
  $count = $_GET['count'];
} else {
  $count = 10000;
}

$sql = "SELECT * FROM `my_table` Limit $from, $count";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  $resultArray = array();
  $tempArray = array();

  while ($row = $result->fetch_assoc()) {
      $tempArray = $row;
      array_push($resultArray, $tempArray);
  }
  //var_dump($resultArray);
  $json = json_encode($resultArray);
} else {
    $json = '{"Json_Result":"Record NOT found!"}';
}
print($json);
$conn->close();

如果从表中检索的数据格式正确,则此方法正常。但是,不幸的是,我的一些行包含一些特殊字符,这些字符在插入时没有转换为正确的格式。如果遇到任何此类行,此代码将失败。在使用var_dump时,我发现这些特殊字符被视为。 在搜索问题时,我发现,要使json_encode正常工作,所有字符必须为utf8格式。但是,我无法弄清楚,在使用json_encode之前我应该​​如何实现它?

0 个答案:

没有答案