How do I convert PHP Array to JSON?

To convert a PHP array to JSON data string, you can use the json_encode() function. The json_encode() function converts passed PHP objects into JSON formatted strings. You can control the flow of the conversion by passing encoding parameters to the json_encode() function. In this PHP Array to JSON example, we use the json_encode() function to convert a PHP Array to a JSON string. Click Execute to run the Convert PHP Array to JSON String Example online and see the result.
How do I convert PHP Array to JSON? Execute
<?php 
$arr = array(
  'US' => 'Washington',  
  'UK' => 'London',
  'Spain' => 'Madrid', 
  'Italy' => 'Rome'
); 

echo json_encode($arr);
?>
Updated: Viewed: 757 times

What is JSON?

JavaScript Object Notation (JSON) is a standard textual format for storing and transmitting data over a network based on JavaScript. Despite its origins in JavaScript, this format is considered language-independent; JSON can use with almost any programming language, including JavaScript, Java, C ++, C #, Go, PHP, Python, and many others.

How to encode a PHP array into a JSON string?

There are two types of arrays in PHP: regular and associative (an associative array uses a key-value structure to store data). The json_encode() function can convert both array types to a JSON data string. We convert an associative array to a JSON string in the example below.

Convert PHP Array to JSON Example
<?php
$arr = array(
  'US' => 'Washington',  
  'UK' => 'London',
  'Spain' => 'Madrid', 
  'Italy' => 'Rome'
); 

echo json_encode($arr);
?>

#output: {"US":"Washington","UK":"London","Spain":"Madrid","Italy":"Rome"}

How to convert a multidimensional associative PHP array to JSON?

The example shows how to convert a multidimensional associative array to JSON using the json_encode() function:

PHP Convert Multidimensional Array to JSON Example
<?php
$arr = array (
  'first"' => array(
    'id'=> 1,
    'product' => 'Pineapple',
    'price' => 90
  ),
  'second' => array(
    'id' => 2,
    'product' => 'Orange',
    'price' => 70
  )
);

echo json_encode($arr);
?>

#output: {"first\"":{"id":1,"product":"Pineapple","price":90},"second":{"id":2,"product":"Orange","price":70}}

See also