Php header utf8 json

PHP header(‘Content-Type: application/json’); is not working

Sorry if it is repeated question, already tried every single suggestion in google and StackOverflow. For some reason, my response header always comes as Content-Type:text/html; charset=UTF-8. I want content type to be json (Content-Type:application/json), Not sure what am I doing wrong. here is my code

  //Make sure that the content type of the POST request has been set to application/json $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : ''; if(strcasecmp($contentType, 'application/json') != 0) < throw new Exception('Content type must be: application/json'); >//Receive the RAW post data. $content = trim(file_get_contents("php://input")); //Attempt to decode the incoming RAW post data from JSON. $decoded = json_decode($content, true); //If json_decode failed, the JSON is invalid. if(!is_array($decoded)) < throw new Exception('Received content contained invalid JSON!'); >$filename = $decoded['filename']; // open csv file if (!($fp = fopen($filename, 'r'))) < die("Can't open file. "); >//read csv headers $key = fgetcsv($fp,"1024",","); // parse csv rows into array $json = array(); while ($row = fgetcsv($fp,"1024",",")) < $json[] = array_combine($key, $row); >// release file handle fclose($fp); // encode array to json header('Content-Type: application/json;charset=utf-8'); echo (json_encode($json, JSON_PRETTY_PRINT)); 

Already tried the following code and I get the same contentType name = «John»; $myObj->age = 30; $myObj->city = «New York»; $myJSON = json_encode($myObj); echo $myJSON; ?>

You may need to disable large chunks of your code to find the problem. If it’s emitting HTML it’s possible you’re just getting an error.

Источник

When to use header(‘Content-Type: application/json’) in PHP

Another thing that could help me if answered, lately I’ve been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?

Читайте также:  Горизонтальная прокрутка изображений html

For example, if you use Ajax to get some sort of content, you’d json_encode() it in your target PHP file — then having that header sets the proper header for returning a proper json-string.

4 Answers 4

Ok for those who are interested, I finally figured out that header(‘Content-Type: application/json’) is used when another page is calling the php script, so that the other page can automatically parse the result as json.

For instance i have in my test.php :

header('Content-type: application/json; charset=utf-8'); $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); //

When I dont have dataType set to «json» or when I don’t have the header in my test.php, the alert gives which is a string (tried with typeof(response), and when I have this header, or dataType:»json», I get [object Object] from the alert. So this header function is there to indicate to the calling pages which type of data it gives back, so that you can know how to deal with it. In my script, if I didn’t have header(‘Content-Type: application/json’) , I would have to parse the response in the javascript like this : JSON.parse(response) in order to make it a json, but with that header, I already have a json object, and I can parse it to html with jSON.stringify(response) .

Источник

JSON в PHP: примеры json_encode, json_decode, работа с кириллицей и utf-8

Подробную документацию всегда можно найти по этой ссылке:

Кодирование при помощи функции json_encode

Функция работает только с кодировкой UTF-8.

Рассмотрим простой пример:

$array = [ 'one' => 1, 'two' => 2, ]; $json = json_encode($array); echo $json;

Результат выполнения кода:

Как видим ассоциативный массив превратился в обычную json строку.

$array = [ 'Ключ 1' => 'Значение 1', 'Ключ 2' => 'Значение 2', 'Ключ 3' => 'Значение 3', ]; $json = json_encode($array); echo $json;

Результат выполнения кода:

Что произошло c кириллицей?

Дело в том, что по умолчанию многобайтовые символы Unicode кодируются как \uXXXX. При раскодировании функцией json_decode они преобразуются в нормальные строки. В некоторых случаях мы можем захотеть избежать этого экранирования, например, чтобы посмотреть как выглядит наш JSON.

Читайте также:  Learn Jquery Html Method

Для этого воспользуемся флагом JSON_UNESCAPED_UNICODE:

$json = json_encode($array, JSON_UNESCAPED_UNICODE); echo $json;

Мы может еще в целях изучения кода преобразовать его в более человеческий вид, при помощи дополнительного флага JSON_PRETTY_PRINT

$json = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); echo $json;

Мы разобрались, как кодировать наши переменные в формат JSON при помощи json_encode.

Другие предопределенные константы с префиксом JSON_ https://www.php.net/manual/ru/json.constants.php

Декодирование c помощью json_decode

Допустим у нас есть строка в формате JSON. Возьмем ее из предыдущего примера:

$var = json_decode($json); var_dump($var);

У нас получился результат:

object(stdClass)#117 (3) < ["Ключ 1"]=>string(18) "Значение 1" ["Ключ 2"]=> string(18) "Значение 2" ["Ключ 3"]=> string(18) "Значение 3" >

Видим, что это тип переменной stdClass. То есть несмотря на то, что мы изначально кодировали в json обычный ассоциативный массив, в результате декодирования у нас получился объект. Подробнее об этом поведении написано здесь: https://phpstack.ru/php/json_decode-kak-perevesti-rezultat-v-massiv.html

Как нам все таки получить обычный массив? Нужно в json_decode передать вторым параметром true:

$var = json_decode($json, true); var_dump($var);
array(3) < ["Ключ 1"]=>string(18) "Значение 1" ["Ключ 2"]=> string(18) "Значение 2" ["Ключ 3"]=> string(18) "Значение 3" >

Теперь мы получили обычный массив. Таким образом разобрались как работать с функцией json_decode для декодирования строки формата JSON.

Обработка ошибок

В случае ошибки, эти функции просто молча возвращают null.

Мы можем проверить, что нам вернулось null и посмотреть какая произошла ошибка следующим образом:

Иногда нам может быть полезно не молчаливо возвращать null, а выкинуть Exception и обработать его. PHP >7.3 предоставляет нам такую возможность.

Это можно сделать при помощи флага JSON_THROW_ON_ERROR

Теперь результат этого кода JsonException с сообщением Syntax error

Более подробно про обработку ошибок JSON:

Как вывести JSON ответ на ajax запрос

Когда к нашему PHP скрипту обращается например javascript с ajax запросом, для того, чтобы подгрузить на страницу новые данные, то часто возникает необходимость ответить в формате JSON.

Читайте также:  Python replace all characters in string

Для того, чтобы это сделать, нужно отправить заголовок Content-type:application/json;charset=utf-8 и просто вывести строку с закодированными данными.

Содержимое файла text_json.php

$array = ['data' => 'ваши данные']; $jsonString = json_encode($array); // переводим данные в JSON строку // отправляем заголовок, который позволит клиенту определить, // что возвращается ответ в формате JSON header('Content-type:application/json;charset=utf-8'); echo $jsonString; // выводим JSON строку exit(); // прекращаем выполнение скрипта

Тем временем в javascript мы можем обратиться к нашему php скрипту таким образом:

Отправка JSON запросов на другой сервер.

Некоторые интернет сервисы принимает запросы в формате JSON. Давайте рассмотрим простой пример как отправить такой запрос.

// httpbin.org - это такой интернет сервис, который помогает нам тестировать запросы. $url = 'https://httpbin.org/anything'; // формируем массив $post_data = [ 'ключ' => 'значение' ]; // преобразуем массив в json $data_json = json_encode($post_data); $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json','Content-Length: ' . strlen($data_json)]); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data_json); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); $response = curl_exec($curl); // сервис вернул нам строку в формате json, давайте ее раскодируем применив знания из этой статьи $result = json_decode($response, true); var_dump($result);

Спасибо за внимание. Если после прочтения у вас остались вопросы — напишите какие.

Источник

Оцените статью