【问题标题】:Emoji from Angularjs $http to PHP json_decode and store in mySQLEmoji 从 Angularjs $http 到 PHP json_decode 并存储在 mySQL 中
【发布时间】:2018-05-25 14:37:50
【问题描述】:

所以我试图将表情符号存储在我的数据库中并将它们返回到我的应用程序中。我用 ionic v1 构建了一个小信使,一切正常。我只想正确存储表情符号并在应用程序中显示它们。我的整个数据库、表和列都设置为 utf8mb4,所以我知道这很好。当我用$http 将它发送到我的php 时,它看起来也不错:{"from_account_id":"xxxx","for_account_id":"xxxx","message":"????"}: 但是当我在php 中打印它时,它看起来像这样:{"from_account_id":"106191","for_account_id":"989014","message":"đ˝"} 并且在我的mysql 中到处我都放了一个表情符号,它显示?。我还能做什么?我还将我的 php 中的标题设置为UTF_8。我知道对此有很多问题,但我已经关注了大多数问题,但它仍然没有解决我的问题。

我存储消息的 php :

<?php
header('Content-Type: text/html; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
include_once 'config.php';

$data = file_get_contents("php://input");
$data = json_decode($data, true);

try {
    $stmt = $dbh->prepare("INSERT INTO `messages` (`message_id`, `from_account_id`, `for_account_id`, `date_read`, `message`)
      VALUES (NULL, :from_account_id, :for_account_id, NULL, :message)");
    $stmt->bindValue(':from_account_id', $data['from_account_id']);
    $stmt->bindValue(':for_account_id', $data['for_account_id']);
    $stmt->bindValue(':message', $data['message']);
    $stmt->execute();
  } catch (PDOException $e) {
          throw $e;
  }
  echo 'Success';

?>

我发送消息的AngularJS 函数:

  $scope.sendMessage = function(for_account_id, message){
    if(for_account_id != null && message != null){
    $http({
      method: 'post',
      url: 'myurl',
      data: {
      from_account_id: $rootScope.unique_id,
      for_account_id: for_account_id,
      message: message,
      },
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(data){
      $scope.thisMessage = null;
      $scope.getMessages();
      $rootScope.webSocket.send($stateParams.chatId + "|" + $rootScope.unique_id  + "|" + 'newMessage');
      $scope.markAsRead();
    })
  }
  }

这是我与数据库的连接:

<?php
$hostname='myhost';
$username='myuser';
$password='mypassword';

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8'); 

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=mydbname;charset=utf8mb4",$username,$password, $options);
    $dbh->query ('SET NAMES utf8');
    $dbh->query ('SET CHARACTER_SET utf8_unicode_ci');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
      echo $e->getMessage();
    }
?>

任何提示或想法我错过了什么?

【问题讨论】:

    标签: php mysql angularjs emoji


    【解决方案1】:

    好吧,我已经解决了我的问题。我这样做的方式可能不是最好的,但它确实有效。所以基本上在数据库中存储 unicode 就这么简单:

    1. 我将要插入数据的文件中的header 更改为:

      header('Content-Type: application/json; charset=utf-8');

    2. 我再次将消息编码为 json,同时像这样插入它:

      $stmt-&gt;bindValue(':message', json_encode($data['message']));

    3. 在再次响应我的应用之前,将标题设置为:

      header('Content-Type: application/json; charset=utf-8');

    我的代码现在看起来像这样:

    <?php
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET');
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    include_once 'config.php';
    
    $data = file_get_contents("php://input");
    $data = json_decode($data, true);
    
    try {
        $stmt = $dbh->prepare("INSERT INTO `messages` (`message_id`, `from_account_id`, `for_account_id`, `date_read`, `message`)
          VALUES (NULL, :from_account_id, :for_account_id, NULL, :message)");
        $stmt->bindValue(':from_account_id', $data['from_account_id']);
        $stmt->bindValue(':for_account_id', $data['for_account_id']);
        $stmt->bindValue(':message', json_encode($data['message']));
        $stmt->execute();
      } catch (PDOException $e) {
        header('Content-Type: text/html; charset=utf-8');
              throw $e;
      }
      header('Content-Type: text/html; charset=utf-8');
      echo 'Success';
    
    ?>
    

    所以这个问题得到了解决,unicodes 存储在我的数据库中。

    然后我又陷入了尴尬的境地,从mysql 获取数据并将其编码为json,同时发送到我的应用程序,即使我绑定了它,我的应用程序也无法将 unicodes 返回到特殊字符使用ng-bind-html 并使用$sce.trustAsHtml()。通常我只是将我的查询结果发送为encoded json,但它并没有像我说的那样工作。所以我所做的是这样的:

    <?php
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *'); 
    header('Access-Control-Allow-Methods: POST, GET');
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    include_once 'config.php';
    
    $data = file_get_contents("php://input");
    $data = json_decode($data, true);
    
    try {
      $stmt = $dbh->prepare("SELECT * from messages WHERE (from_account_id = :unique_id AND for_account_id = :user_2) OR (from_account_id = :user_2 AND for_account_id = :unique_id)");
      $stmt->bindValue(':unique_id', $data['user_1']);
      $stmt->bindValue(':user_2', $data['user_2']);
      $stmt->execute();
      } catch (PDOException $e) {
              throw $e;
          }
    
      $rows = $stmt->rowCount();
      $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
      if ($rows > 0){
        $i = 0;
        echo "[";
        foreach ($result as $key => $value){
          $i++;
          echo "{";
          echo '"message_id"' . ":" . '"' .$value['message_id']. '"' .", ";
          echo '"from_account_id"' . ":" . '"' .$value['from_account_id']. '"' .", ";
          echo '"for_account_id"' . ":". '"' .$value['for_account_id']. '"' .", ";
          echo '"date_sent"' . ":" . '"' .$value['date_sent']. '"' .", ";
          echo '"date_read"' . ":" . '"' .$value['date_read']. '"' .", ";
          echo '"message"' . ":" . '"' .str_replace("\n", "</br>", json_decode($value['message'])). '"' ;
          echo "}";
          if($i != $rows){
            echo ",";
          }
          if($i == $rows){
            echo "]";
          }
          echo "\n";
        }
        exit;
      }
      else {
        echo 'Something went wrong';
        exit;
      }
    
    ?>
    

    将解码的json 发送到我的 angularjs 得到的字符串中,因为我自己制作的真实 json 是解决方案。

    我已将答案添加到此问题中,因为也许有人会遇到同样的麻烦,这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 2014-09-28
      • 2018-06-07
      • 2014-05-10
      • 2015-12-09
      • 1970-01-01
      相关资源
      最近更新 更多