Avatar ·

How to properly return JSON from a PHP script?

Hello everyone! I'm a beginner in PHP and trying to make a simple API for my project. I need the PHP script to return data in JSON format, which will then be processed by JavaScript on the frontend.\n\nThe problem is that when I make a request to my script, I get not only JSON but also some garbage. For example, here is my code:\n\n```php\n "Ivan", "age" => 30);\necho json_encode($data);\n?>\n```\n\nWhen I open this script in the browser, I see: `{"name":"Ivan","age":30}`. But if I make a request via JavaScript or Postman, sometimes I get an empty response or a JSON parsing error. I tried adding `header('Content-Type: application/json');`, but it doesn't help. \n\nI also noticed that if there are any errors or warnings in the script (for example, `Noti