How to send json instead of html from php?

by dalton_moen , in category: PHP General , 10 months ago

How to send json instead of html from php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 10 months ago

@dalton_moen 

To send JSON instead of HTML from PHP, you can follow these steps:

  1. Create a PHP script that generates the JSON data you want to send. This can be done by creating an array or an object in PHP and then encoding it into a JSON string using the json_encode function.
1
2
3
4
5
6
7
$data = array(
    'name' => 'John',
    'age' => 30,
    'city' => 'New York'
);

$jsonData = json_encode($data);


  1. Set appropriate headers in your PHP script to indicate that you are sending JSON data. You can use the header function to set the Content-Type header to "application/json".
1
header('Content-Type: application/json');


  1. Finally, echo or print the JSON data from your PHP script.
1
echo $jsonData;


  1. Save and run your PHP script. It will send the JSON data instead of rendering HTML.


Make sure that the PHP script does not output anything else except the JSON data, as it may result in an invalid JSON response.