I want to return JSON from a PHP script.
Do I just echo the result? Do I have to set the Content-Type
header?
Whenever you are trying to return JSON response for API or else make sure you have proper headers and also make sure you return a valid JSON data.
Here is the sample script which helps you to return JSON response from PHP array or from JSON file.
PHP Script (Code):
'HealthMatters',
'id' => '072b3d65-9168-49fd-a1c1-a4700fc017e0',
'sentiment' => [
'negative' => 44,
'positive' => 56,
],
'total' => '3400',
'users' => [
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'rayalrumbel',
'text' => 'Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'mikedingdong',
'text' => 'Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'ScottMili',
'text' => 'Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'yogibawa',
'text' => 'Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
],
];
// Output, response
echo json_encode($json_var);
JSON File (JSON DATA):
{
"hashtag": "HealthMatters",
"id": "072b3d65-9168-49fd-a1c1-a4700fc017e0",
"sentiment": {
"negative": 44,
"positive": 56
},
"total": "3400",
"users": [
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "rayalrumbel",
"text": "Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "mikedingdong",
"text": "Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "ScottMili",
"text": "Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "yogibawa",
"text": "Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
}
]
}
JSON Screeshot: