Current Location: Home> Latest Articles> How to Use PHP's json_encode Function to Convert Variables to JSON Format Strings

How to Use PHP's json_encode Function to Convert Variables to JSON Format Strings

M66 2025-06-18

How to Use PHP's json_encode Function to Convert Variables to JSON Format Strings

In PHP development, it is common to need to convert data to a JSON format string, especially when dealing with front-end data transfer and processing. Fortunately, PHP provides a powerful function — json_encode — that allows you to easily convert PHP variables to standard JSON format strings.

Example 1: Converting a Simple Array to a JSON Format String

$fruits = array("apple", "banana", "orange");
$jsonString = json_encode($fruits);
echo $jsonString;

Output:

["apple","banana","orange"]

Example 2: Converting an Associative Array to a JSON Format String

$person = array(
    "name" => "Tom",
    "age" => 25,
    "city" => "New York"
);
$jsonString = json_encode($person);
echo $jsonString;

Output:

{"name":"Tom","age":25,"city":"New York"}

Example 3: Converting a PHP Object to a JSON Format String

class Person {
    public $name;
    public $age;
    public $city;
}
<p>$person = new Person();<br>
$person->name = "Tom";<br>
$person->age = 25;<br>
$person->city = "New York";</p>
<p>$jsonString = json_encode($person);<br>
echo $jsonString;<br>

Output:

{"name":"Tom","age":25,"city":"New York"}

Enhance Readability: Using JSON_PRETTY_PRINT

In addition to simple conversion, json_encode offers an option: JSON_PRETTY_PRINT, which formats the output, making the generated JSON string easier to read.

$person = array(
    "name" => "Tom",
    "age" => 25,
    "city" => "New York"
);
<p>$jsonString = json_encode($person, JSON_PRETTY_PRINT);<br>
echo $jsonString;<br>

Output:

{
    "name": "Tom",
    "age": 25,
    "city": "New York"
}

Conclusion:

With PHP's json_encode function, developers can easily convert PHP variables (such as arrays, associative arrays, or objects) into JSON format strings, which is crucial for data transfer. With different parameter options, json_encode can not only meet basic conversion needs but also offer more customized output formats. Mastering these techniques will help you handle data more efficiently in your development projects.