Php get request json response

Receive JSON object from HTTP Get in PHP

I am trying to implement a php client that sends an HTTP GET to the server which sends back a JSON object with the return information. I know how to decode the JSON once my php script has received it, but how would I go about actually getting it? EDIT: Note — I send the server an HTTP GET, and it generates and sends back a JSON file. It is not a file sitting on the server.

2 Answers 2

$json = file_get_contents('http://somesite.com/getjson.php'); 

This does not work. I have to send an HTTP GET to the server, which generates and returns a JSON file. It is not just a file out there which I can access. Because of that, when I try to do this, I get an error that says «failed to open stream».

PHP has to be configured appropriately for file_get_contents() to retrieve via HTTP and other protocols, but if it is, I second the recommendation to use it. It sounds like it may not be in your case though. Can you provide some info about your PHP configuration? If you have cURL, that’s another possibility, as mentioned by the earlier commenter.

You have to use cURL or file_get_contents (both of them need to be enabled on php.ini file) to make them work, then your $json variable will be Ok.

Sorry. The server I was running it on did not have PHP configured to run file_get_contents(). I fixed it, and it worked.

Browsers act differently based on what the server responds. It does not matter what type of request you make to the server (be it GET, POST, etc), but to return JSON as a response you have to set the header in the script you make the request to:

header('Content-Type: application/json;charset=utf-8;'); 

And then echo the JSON string, for example:

//. populating your result data array here. // // Print out the JSON formatted data echo json_encode($myData); 

User agent will then get the JSON string. If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this:

//. AJAX request here. // // Parse result to JavaScript object var myData=JSON.parse(XMLHttp.responseText); 

The header itself is not -really- necessary, but is sort-of good practice. JSON.parse() can parse the response regardless.

Источник

Get JSON from URL in PHP

In this tutorial, I’m going to show you how to get json from url in php script. JSON has become a popular way to exchange data and web services outputs in json format. To send a HTTP request and parse JSON response from URL is fairly simple in php but newbies may find how to parse json difficult.

Let’s see how to build a php json parser script. For this script, I’m going to access Google MAP web service via API and get latitude and longitude co-ordinates for a location. Google map api produces both json/xml output. But for this example I’m going to get the json response and show you how to parse json object to retrieve the geo-metric details.

Читайте также:  Link type javascript src

php-get-json-from-url

How to Get JSON from URL in PHP

This is the php script to read the json data from url.

results[0]->geometry->location->lat; $lng = $json->results[0]->geometry->location->lng; echo "Latitude: " . $lat . ", Longitude: " . $lng; // output // Latitude: 40.6781784, Longitude: -73.9441579 ?>

The above php script sends a HTTP request to Google MAP web service along with a parameter containing a physical address. The API in turn returns the geometric co-ordinates for the address as json string — which we further decode into a php object and parse it to retrieve the latitude and longitude details.

The php function file_get_contents($url) send a http request to the provided url and returns json data.

The function json_decode($json) decodes the provided json string and returns as a PHP object.

As simple as that you can parse json response. That was all about getting json from url in php.

Источник

Returning JSON from a PHP Script

I want to return JSON from a PHP script. Do I just echo the result? Do I have to set the Content-Type header?

Always set the Content-Type header for json, to avoid XSS. Observe the difference between these two scripts: «»]); ?> and «»]); ?> For more information see: security.stackexchange.com/questions/169427/… [Not able to submit an answer due to reputation requirement]

20 Answers 20

While you’re usually fine without it, you can and should set the Content-Type header:

If I’m not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn’t be necessary).

just in case: you should use header() commands only in addition with output buffering to avoid «headers already sent» warnings

It’s good practice to always put your header() statements as far to the top of the page as possible so that when you add more code, you aren’t tempted to insert code before the header() statement which could break things if you start outputting.

@mikepote I actually don’t think it’s necessary to have the header command at the top of the PHP file. If you’re inadvertently spitting out stuff and that’s tripping up your header command, you just need to fix your code because it’s broken.

@KrzysztofKalinowski no, the PHP file doesn’t need to be UTF-8 encoded. the output MUST be UTF-8 encoded. Those wrong statements doesn’t help non-experienced users to learn how to avoid things from breaking, but it helps to grow myths on them and never learning which role does encodings play on streams and how they work.

@timdev don’t forget to call exit(); of die(); right after echo json_encode($data); , otherwise random data from your script (e.g profiling) might get appended to your json response.

A complete piece of nice and clear PHP code returning JSON is:

$option = $_GET['option']; if ( $option == 1 ) < $data = [ 'a', 'b', 'c' ]; // will encode to JSON array: ["a","b","c"] // accessed as example in JavaScript like: result[1] (returns "b") >else < $data = [ 'name' =>'God', 'age' => -1 ]; // will encode to JSON object: // accessed as example in JavaScript like: result.name or result['name'] (returns "God") > header('Content-type: application/json'); echo json_encode( $data ); 

According to the manual on json_encode the method can return a non-string (false):

Returns a JSON encoded string on success or FALSE on failure.

When this happens echo json_encode($data) will output the empty string, which is invalid JSON.

Читайте также:  Python connectionreseterror 104 connection reset by peer

json_encode will for instance fail (and return false ) if its argument contains a non UTF-8 string.

This error condition should be captured in PHP, for example like this:

 json_last_error_msg()]); if ($json === false) < // This should not happen, but we go all the way now: $json = ''; > // Set HTTP response status code to: 500 - Internal Server Error http_response_code(500); > echo $json; ?> 

Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly.

In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.

Read more about dealing with JSON errors in PHP’s Documentation.

There’s no charset parameter for JSON; see the note at the end of tools.ietf.org/html/rfc8259#section-11: «No ‘charset’ parameter is defined for this registration. Adding one really has no effect on compliant recipients.» (JSON must be transmitted as UTF-8 per tools.ietf.org/html/rfc8259#section-8.1, so specifying that it’s encoded as UTF-8 is a bit redundant.)

Thanks for highlighting that, @PatrickDark. Redundant charset parameter removed from HTTP header string.

Try json_encode to encode the data and set the content-type with header(‘Content-type: application/json’); .

This question got many answers but none cover the entire process to return clean JSON with everything required to prevent the JSON response to be malformed.

 /* * returnJsonHttpResponse * @param $success: Boolean * @param $data: Object or Array */ function returnJsonHttpResponse($success, $data) < // remove any string that could create an invalid JSON // such as PHP Notice, Warning, logs. ob_clean(); // this will clean up any previously added headers, to start clean header_remove(); // Set the content type to JSON and charset // (charset can be set to something else) header("Content-type: application/json; charset=utf-8"); // Set your HTTP response code, 2xx = SUCCESS, // anything else will be error, refer to HTTP documentation if ($success) < http_response_code(200); >else < http_response_code(500); >// encode your PHP Object or Array into a JSON string. // stdClass or array echo json_encode($data); // making sure nothing is added exit(); > 

thnx for the ob_clean reference. I had a leading line that was jacking up my fetch response.json() calls.

Set the content type with header(‘Content-type: application/json’); and then echo your data.

It is also good to set the access security — just replace * with the domain you want to be able to reach it.

 '1', 'value1'=> 'value1', 'value2'=> 'value2' ); echo json_encode($response); ?> 

What does it mean if this doesn’t work? For example, to restrict only to calls from CodePen, I tried header(‘Access-Control-Allow-Origin: https://cdpn.io’); , but I can still load the page from my own browser.

it is used for blocking cross scripting (one script calling another page). So you will be able to load it directly from your browser, but you cant load it from another domain using script.

A simple function to return a JSON response with the HTTP status code.

function json_response($data=null, $httpStatus=200) < header_remove(); header("Content-Type: application/json"); http_response_code($httpStatus); echo json_encode($data); exit(); >

header_remove , and explicitly setting the http response is a good idea; although setting status and then http_response seems redundant. Might also want to add an exit statement to the end. I combined your function with @trincot ‘s: stackoverflow.com/a/35391449/339440

Читайте также:  Java datainputstream readfully eofexception

Using JS FetchAPI, could you extend your answer on how to receive sent data? fetch(. ).then(res => res.json()).then(data => /* do smth */).catch(e => console.error(e)) works great when response is 200 , but how to get $data on 500 to show the exact error thrown in PHP in the .catch() method in JS?

To achieve that you have to wrap your code in a try catch: try < /* code. */ json_response('Success!', 200); >catch (\Exception $e) < json_response($e->getMessage(), 500); >

header('Content-Type: application/json'); 

will make the job. but keep in mind that :

  • Ajax will have no problem to read json even if this header is not used, except if your json contains some HTML tags. In this case you need to set the header as application/json.
  • Make sure your file is not encoded in UTF8-BOM. This format add a character in the top of the file, so your header() call will fail.

If you want js object use header content-type:

If you want only json : remove header content-type attribute, just encode and echo.

The answer to your question is here,

The MIME media type for JSON text is application/json.

so if you set the header to that type, and output your JSON string, it should work.

If you need to get json from php sending custom information you can add this header(‘Content-Type: application/json’); before to print any other thing, So then you can print you custome echo ‘valor.'»,»moneda»:»‘.$moneda[0]->nombre.'»,»simbolo»:»‘.$moneda[0]->simbolo.'»>’;

Yeah, you’ll need to use echo to display output. Mimetype: application/json

If you query a database and need the result set in JSON format it can be done like this:

fetch_array()) < $rows[] = $row; >//Return result to jTable $qryResult = array(); $qryResult['logs'] = $rows; echo json_encode($qryResult); mysqli_close($db); ?> 

For help in parsing the result using jQuery take a look at this tutorial.

This is a simple PHP script to return male female and user id as json value will be any random value as you call the script json.php .

user_id = rand(0, 10); $myObj->male = rand(0, 5); $myObj->female = rand(0, 5); $myJSON = json_encode($myObj); echo $myJSON; ?> 

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' => '>', ], [ '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' => '>', ], [ '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' => '>', ], [ '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' => '>', ], ], ]; // Output, response echo json_encode($json_var); 

JSON File (JSON DATA):

Источник

Оцените статью