0

I'd like to output a utf8 json object in my php code:

 <?php
 header('Content-type: text/html; charset=utf-8');
 header('Content-Type: application/json');
 $response= array();
 $product = array();
 $product["title"]="عنوان";
 $product["nim_body"]="بدنه";   
 $product["writer"]="نویسنده"; 
 array_push($response,$product);
 echo json_encode($response,JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);

and my output is like picture:

sepehr
  • 17,110
  • 7
  • 81
  • 119
nazanin
  • 729
  • 1
  • 6
  • 13
  • You *can* pass raw multibyte sequences, but unless you have a damned good reason to then you should not. Multibyte UTF8 sequences are not 7-bit safe and may cause your data to become corrupted in transit if you're not careful. See: http://stackoverflow.com/a/594881/1064767 – Sammitch Jan 09 '17 at 21:52

1 Answers1

2

Use JSON_UNESCAPED_UNICODE flag.

JSON_UNESCAPED_UNICODE (integer) Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.

There's no good reason to pretty print a json object unless you're printing into a file for example. If you need this for readability reasons, use a browser extension instead.

One more note; when responding with JSON objects, it's not enough to only output a valid object. You also need to set the content type header; Content-Type: application/json. You're setting this twice; once to text/html and then to application/json. Drop the former.

sepehr
  • 17,110
  • 7
  • 81
  • 119