PHP and JSON are two technologies that can be used together to exchange data between web applications. Here are some examples of how to use PHP and JSON:
- Encoding data as JSON:
$data = array('name' => 'John', 'age' => 30);
$json = json_encode($data);
echo $json;
In this example, an array called $data
is defined with two key-value pairs representing a person’s name and age. The json_encode()
function is used to convert the array to a JSON-encoded string, which is then printed to the screen.
- Decoding JSON data:
$json = '{"name":"John","age":30}';
$data = json_decode($json);
echo $data->name;
echo $data->age;
In this example, a JSON-encoded string is defined using curly braces to represent an object with two properties: “name” and “age”. The json_decode()
function is used to convert the JSON string to a PHP object, which can be accessed using the arrow operator (->
) to access its properties.
- Sending JSON data with an HTTP request:
$data = array('name' => 'John', 'age' => 30);
$json = json_encode($data);
$ch = curl_init('http://example.com/api');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
In this example, an array called $data
is defined with two key-value pairs representing a person’s name and age. The json_encode()
function is used to convert the array to a JSON-encoded string, which is then sent with an HTTP request using cURL. The request is set to use a JSON content type header, and the response from the server is stored in a variable called $response
.
By using PHP and JSON together, developers can create web applications that communicate with other applications or services using a standardized data format that is easy to parse and manipulate.