nazanin
nazanin

Reputation: 749

how to use utf-8 with json in php file

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:

Upvotes: 0

Views: 2240

Answers (1)

sepehr
sepehr

Reputation: 18455

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.

Upvotes: 2

Related Questions