Home > Article > Backend Development > How to convert PHP array to JSON gracefully
In PHP, you can convert an array to JSON format using the json_encode() function, which accepts an array and returns a JSON string. It supports several options, including JSON_FORCE_OBJECT (forces arrays to be encoded as objects), JSON_NUMERIC_CHECK (keeps numeric key-value pairs as numeric values), JSON_UNESCAPED_SLASHES (disables forward slash escaping), and JSON_UNESCAPED_UNICODE (disables Unicode character escaping). JSON data can be sent to the server via AJAX and then parsed back into a PHP array using the json_decode() function.
Elegantly convert PHP array to JSON
In PHP, converting an array to JSON format is very easy, just Use the json_encode()
function. This function accepts an array as input and returns a JSON encoded string. For example:
$array = [ 'name' => 'John Doe', 'age' => 30 ]; $json = json_encode($array); echo $json; // 输出: {"name":"John Doe","age":30}
Learn more
json_encode()
The function also supports some useful options that allow you to control the JSON format of the output. Some of the options include:
Practical Case
Suppose we have an array that contains information about users stored in a database. We want to convert this array to JSON format to send to the server via AJAX request.
$user = [ 'id' => 1, 'name' => 'John Doe', 'email' => 'john.doe@example.com' ]; $json = json_encode($user);
We can use AJAX to send $json
variables as data as follows:
$.ajax({ url: 'save_user.php', type: 'POST', data: { user: json }, success: function(response) { // 操作服务器响应 } });
On the server side, we can use json_decode()
Function to parse JSON string back into PHP array:
<?php $json = $_POST['user']; $user = json_decode($json, true); // 第二个参数为 true 将结果作为关联数组而不是对象返回 // 对 $user 数组进行操作... ?>
The above is the detailed content of How to convert PHP array to JSON gracefully. For more information, please follow other related articles on the PHP Chinese website!