php-json output web service problem with utf-8 cha

2019-05-31 07:05发布

I am new to PHP & JSON and based on a tutorial I made a simple web service which returns the contents of a table of a mysql db.

The output is in both XML and JSON and the database caracter set is UTF-8. my problem is that some fields contain Greek characters and do not appear correctly in the JSON output format (in XML everything is fine). Any idea what might be wrong?

The PHP file is the following:

<?php

/* require the place_name_en as the parameter */

      /* soak in the passed variable or set our own */
      $number_of_places = isset($_GET['num']) ? intval($_GET['num']) : 1; //10 is the default
      $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default


       /* connect to the db */
      $link = mysql_connect('xxx','xxx','xxx') or die('Cannot connect to the DB');

     mysql_select_db('foodbar',$link) or die('Cannot select the DB');
     mysql_set_charset('utf8',$link);
     mysql_query('set names utf8'); 

      /* grab the posts from the db */
      $query = 'SELECT * FROM test';
      $result = mysql_query($query,$link) or die('Errant query:  '.$query);


      /* create one master array of the records */
      $posts = array();

      if(mysql_num_rows($result)) {
        while($place = mysql_fetch_assoc($result)) {
          $places[] = array('place'=>$place);

      }

      }

      if($format == 'json') {
      /* output in json format */
            header('Content-type: application/json');
            echo json_encode(array('places'=>$places));
    }
      else {

      /* output in xml format */

        header('Content-type: text/xml; charset=utf-8');
         echo '<?xml version="1.0" encoding="utf-8"?>';
        echo '<places>';
        foreach($places as $index => $place) {
          if(is_array($place)) {
            foreach($place as $key => $value) {
              echo '<',$key,'>';
              if(is_array($value)) {
                foreach($value as $tag => $val) {
                  /*echo '<',$tag,'>',htmlentities($val,ENT_QUOTES,"utf-8"),'</',$tag,'>';*/
                        echo '<',$tag,'>',$val,'</',$tag,'>';
                }
              }
              echo '</',$key,'>';
            }
          }
        }
        echo '</places>';
        }

      @mysql_close($link);

?>

You can test the xml output here.

But when json format is returned there is a problem with Greek characters. they appear like:

\u03b4\u03b4\u03b5\u03c3\u03c3\u03b4\u03b4\u03c6

Any idea? Thank you in advance!

P.S. DB settings: MySQL charset: UTF-8 Unicode (utf8) and MySQL connection collation: utf_8_unicode_ci

1条回答
在下西门庆
2楼-- · 2019-05-31 07:23

json_encode() encodes unicode characters to \uxxxx sequences. It's normal. JS will understand them

查看更多
登录 后发表回答