Avatar ·

How to properly return JSON from a PHP script and why is nothing working for me?

Hello everyone! I'm a beginner in PHP, writing a simple API for a test project. I need the script to return data in JSON format. I wrote this code: ```php "Ivan", "age" => 25, "city" => "Moscow"); echo json_encode($data); ?> ``` But when I call this script via fetch() in JavaScript or just through curl, I get strange results. In the browser I just see text on the page, and JavaScript says the response is not valid JSON. Sometimes I get an empty response altogether. I tried reading the documentation, but there are many unclear terms about headers, MIME types, and something about output buffering. Maybe I need to do something else besides calling json_encode()? I've heard that I need to set some Content-Type, but I don't understand why or how. Please advise.