Nội dung chínhJavaScript Object Notation
There are no user contributed notes for this page.
JSON
JSON [JavaScript Object Notation] is a lightweight data-interchange format. Itis easily read and written by humans and parsed and generated by machines. Theapplication/json is the official Internet media type for JSON. TheJSON filename extension is .json.
Bạn đang xem: Xử lý json trong php dùng Để làm gì? xử lý json trong php
The json_encode function returns the JSON representation of thegiven value. The json_decode takes a JSON encoded string andconverts it into a PHP variable.
PHP frameworks such as Symfony and Laravel have built-in methods that workwith JSON.
PHP JSON encode
In the following example, we use the json_encode function.
The example transforms a PHP array into a JSON string.
$ php -S localhost:8000 encode.phpWe start the server and locate to the localhost:8000.
Figure: JSON view in Firefox
Modern web browsers show JSON view for JSON data when they receive an appropriatecontent type in the header of the response.
PHP JSON decode
In the following example, we use the json_decode function.
The example transforms a JSON string into a PHP variable.
Xem thêm: Tải Game Vxp Free - Cửa Hàng Game & Apps
$ php -S localhost:8000 decode.phpWe start the server.
$ curl localhost:8000John Doe is a gardenerWe send a GET request with curl.
< {"name": "John Doe", "occupation": "gardener", "country": "USA"}, {"name": "Richard Roe", "occupation": "driver", "country": "UK"}, {"name": "Sibel Schumacher", "occupation": "architect", "country": "Germany"}, {"name": "Manuella Navarro", "occupation": "teacher", "country": "Spain"}, {"name": "Thomas Dawn", "occupation": "teacher", "country": "New Zealand"}, {"name": "Morris Holmes", "occupation": "programmer", "country": "Ireland"}>This is the JSON data.
Name Occupation Country
name; ?> | occupation; ?> | country; ?> |
In the code example, we read the file with file_get_contents anddecode it into an PHP array with json_decode. Later, we placethe data into a table utilizing PHP foreach loop.
PHP JSON read from database
In the following example, we read data from an SQLite database and returnit in JSON.
BEGIN TRANSACTION;DROP TABLE IF EXISTS cities;CREATE TABLE cities[id INTEGER PRIMARY KEY, name TEXT, population INTEGER];INSERT INTO cities[name, population] VALUES["Bratislava", 432000];INSERT INTO cities[name, population] VALUES["Budapest", 1759000];INSERT INTO cities[name, population] VALUES["Prague", 1280000];INSERT INTO cities[name, population] VALUES["Warsaw", 1748000];INSERT INTO cities[name, population] VALUES["Los Angeles", 3971000];INSERT INTO cities[name, population] VALUES["New York", 8550000];INSERT INTO cities[name, population] VALUES["Edinburgh", 464000];INSERT INTO cities[name, population] VALUES["Berlin", 3671000];COMMIT;This SQL code creates a cities table in SQLite.
$ sqlite3 test.dbsqlite> .read cities.sqlsqlite> SELECT * FROM cities;1|Bratislava|4320002|Budapest|17590003|Prague|12800004|Warsaw|17480005|Los Angeles|39710006|New York|85500007|Edinburgh|4640008|Berlin|3671000With the sqlite3 command line tool, we generate an SQLite databaseand create the cities table.
query["SELECT * FROM cities"];$cities = ;while [$row = $res->fetchArray[]] { $cities = $row;}header["Content-type:application/json;charset=utf-8"];echo json_encode[ $cities>];In the example, we retrieve the data from the database and return it as JSON.
PHP JSON and JS fetch API
In the following example, we use JavaScript fetch API to get the JSON data from a PHP script.
- Ngôn ngữ php là gì, ngôn ngữ lập trình php Được dùng Để làm gì,
- Comparing two dates in php
- Hướng dẫn tự học lập trình php online a
- Giao trinh php
Tôi có
một đoạn script PHP liên quan đến nhiều ngôn ngữ. Thật không may, bất cứ khi nào tôi cố gắng sử dụng json_encode
, mọi đầu ra Unicode đều được chuyển đổi thành các thực thể thập lục phân. Đây có phải là hành vi dự kiến? Có cách nào để chuyển đổi đầu ra thành các ký tự UTF-8 không?
Đây là một ví dụ về những gì tôi đang thấy:
ĐẦU VÀO
echo $text;
ĐẦU RA
База данни грешка.
ĐẦU VÀO
json_encode[$text];
ĐẦU RA
"\u0411\u0430\u0437\u0430 \u0434\u0430\u043d\u043d\u0438 \u0433\u0440\u0435\u0448\u043a\u0430."
- php
- encoding
- json
111 hữu ích 0 bình luận 149k xem chia sẻ
answer
264
Kể từ PHP / 5.4.0, có một tùy chọn được gọi "JSON_UNESCAPED_UNICODE"
. Kiểm tra xem nó:
//se2.php.net/json_encode
Vì vậy, bạn nên thử:
json_encode[ $text, JSON_UNESCAPED_UNICODE ];
264 hữu ích 5 bình luận chia sẻ
answer
53
JSON_UNESCAPED_UNICODE có sẵn trên phiên bản PHP 5.4 trở lên.
Đoạn mã sau dành cho Phiên bản 5.3.
CẬP NHẬT
html_entity_decode
hiệu quả hơn một chút so vớipack
+mb_convert_encoding
.[*SKIP][*FAIL]
bỏ qua dấu gạch chéo ngược chính nó và các ký tự được chỉ định bằngJSON_HEX_*
cờ.
function raw_json_encode[$input, $flags = 0] {
$fails = implode['|', array_filter[array[
'\\\\',
$flags & JSON_HEX_TAG ? 'u003[CE]' : '',
$flags & JSON_HEX_AMP ? 'u0026' : '',
$flags & JSON_HEX_APOS ? 'u0027' : '',
$flags & JSON_HEX_QUOT ? 'u0022' : '',
]]];
$pattern = "/\\\\[?:[?:$fails][*SKIP][*FAIL]|u[[0-9a-fA-F]{4}]]/";
$callback = function [$m] {
return html_entity_decode["$m[1];", ENT_QUOTES, 'UTF-8'];
};
return preg_replace_callback[$pattern, $callback, json_encode[$input, $flags]];
}
53 hữu ích 5 bình luận chia sẻ
answer
2
Một giải pháp là đầu tiên mã hóa dữ liệu và sau đó giải mã nó trong cùng một tệp:
$string =json_encode[$input, JSON_UNESCAPED_UNICODE] ;
echo $decoded = html_entity_decode[ $string ];
2 hữu ích 0 bình luận chia sẻ
answer
1
Bạn thích đặt bộ ký tự và uniccted unicode
header['Content-Type: application/json;charset=utf-8'];
json_encode[$data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT];
1 hữu ích 1 bình luận chia sẻ
answer
0
Hàm raw_json_encode [] ở trên không giải quyết được vấn đề cho tôi [vì một số lý do, hàm gọi lại đã phát sinh lỗi trên máy chủ PHP 5.2.5 của tôi].
Nhưng giải pháp khác này đã thực sự làm việc.
//www.experts-exchange.com/questions/28628085/json-encode-fails-with-special-char character.html
Tín dụng nên đến Marco Gasi . Tôi chỉ gọi hàm của anh ấy thay vì gọi json_encode []:
function jsonRemoveUnicodeSequences[ $json_struct ]
{
return preg_replace[ "/\\\\u[[a-f0-9]{4}]/e", "iconv['UCS-4LE','UTF-8',pack['V', hexdec['U$1']]]", json_encode[ $json_struct ] ];
}
0 hữu ích 0 bình luận chia sẻ
answer
0
json_encode[$text, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES];
0 hữu ích 0 bình luận chia sẻ
answer
1
Vì bạn đã hỏi:
Có cách nào để chuyển đổi đầu ra thành các ký tự UTF-8 không?
Một giải pháp khác là sử dụng utf8_encode .
Điều này sẽ mã hóa chuỗi của bạn đến UTF-8
.
ví dụ
foreach [$rows as $key => $row] {
$rows[$key]["keyword"] = utf8_encode[$row["keyword"]];
}
echo json_encode[$rows];
1 hữu ích 2 bình luận chia sẻ
answer
5
Đây có phải là hành vi dự kiến?
các json_encode[]
công trình chỉ với dữ liệu UTF-8 mã hóa.
có lẽ bạn có thể nhận được câu trả lời để chuyển đổi nó ở đây: cyrillic-character-in-phps-json-encode
5 hữu ích 0 bình luận chia sẻ