here is my PHP script.
do2:locu alexus$ cat venuesearch.php
<?php
$KEY='XXXXXXXXXXXXXXX';
$URL='http://api.locu.com/v1_0/venue/search/?api_key=';
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $URL.$KEY);
curl_setopt($ch, CURLOPT_HEADER,0);
print_r(json_decode(curl_exec($ch),TRUE));
?>
do2:locu alexus$
locu service provides output in JSON format. When I run script I'm getting output all in long single line.
sample of output:
do2:locu alexus$ php venuesearch.php
{"meta": {"cache-expiry": 3600, "limit": 25}, "objects": [{"categories": ["restaurant"], "country": "United States",..........
What am I missing? How can I access each of those variables? maybe it makes sense to convert it into XML?
* UPDATE * : .. in example #1 of PHP: json_decode - Manual shows formated output, if I use true then I get array, I'm not getting neither formatet output nor array.
Try adding:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
before execution.
It looks like the execution is simply printing the response rather than returning it as a string to be processed by json_decode.
You should look at the original data:
$json = curl_exec($ch);
var_dump($json);
Your described output is only possible if the API returns a json encoded json string, like that:
"{\"meta\": {\"cache-expiry\": 3600, \"limit\": 25}, \"objects\": [{\"categories\": [\"restaurant\"], \"country\": \"United States\",.......... '
(note the outer quotes, they are part of the string)
This is very weird and definitly a bug in the API but the only way to get around it is to decode it twice:
$data = json_decode(json_decode($json));
Edit: Forget that, Stegrex has figured it out.
Related
I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.
When I print :
echo $_POST;
I get:
Array
I get nothing when I try this:
if ( $_POST ) {
foreach ( $_POST as $key => $value ) {
echo "llave: ".$key."- Valor:".$value."<br />";
}
}
I get nothing when I try this:
$string = $_POST['operation'];
$var = json_decode($string);
echo $var;
I get NULL when I try this:
$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );
When I do:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
I get:
NULL
The JSON format is (according to payment site documentation):
{
"operacion": {
"tok": "[generated token]",
"shop_id": "12313",
"respuesta": "S",
"respuesta_details": "respuesta S",
"extended_respuesta_description": "respuesta extendida",
"moneda": "PYG",
"monto": "10100.00",
"authorization_number": "123456",
"ticket_number": "123456789123456",
"response_code": "00",
"response_description": "Transacción aprobada.",
"security_information": {
"customer_ip": "123.123.123.123",
"card_source": "I",
"card_country": "Croacia",
"version": "0.3",
"risk_index": "0"
}
}
}
The payment site log says everything is OK. What’s the problem?
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:
$_POST = json_decode(file_get_contents('php://input'), true);
This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.
It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Use $HTTP_RAW_POST_DATA instead of $_POST.
It will give you POST data as is.
You will be able to decode it using json_decode() later.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
Get data from php project user bellow like
// takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
echo $data['requestCode'];
echo $data['mobileNo'];
echo $data['password'];
Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:
"http://yourdomain.com/read_result.php"
should be
"https://yourdomain.com/read_result.php"
or either way.
add or remove the "s" to match your URL.
If all of the above answers still leads you to NULL input for POST, note that POST/JSON in a localhost setting, it could be because you are not using SSL. (provided you are HTTP with tcp/tls and not udp/quic)
PHP://input will be null on non-https and if you have a redirect in the flow, trying configuring https on your local as standard practice to avoid various issues with security/xss etc
The decoding might be failing (and returning null) because of php magic quotes.
If magic quotes is turned on anything read from _POST/_REQUEST/etc. will have special characters such as "\ that are also part of JSON escaped. Trying to json_decode( this escaped string will fail. It is a deprecated feature still turned on with some hosters.
Workaround that checks if magic quotes are turned on and if so removes them:
function strip_magic_slashes($str) {
return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}
$operation = json_decode(strip_magic_slashes($_POST['operation']));
I got "null" when I tried to retrieve a posted data in PHP
{
"product_id": "48",
"customer_id": "2",
"location": "shelf", // shelf, store <-- comments create php problems
"damage_types":{"Pests":1, "Poke":0, "Tear":0}
// "picture":"jhgkuignk" <-- comments create php problems
}
You should avoid commenting JSON code even if it shows no errors
I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.
// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';
// get mpdf instance
$mpdf = new \Mpdf\Mpdf();
// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';
// encode $_POST data to json
$json = json_encode($_POST);
// init curl > pass the url of the php file we want to pass
// data to and then print out to pdf
$ch = curl_init($mysrcfile);
// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
// exec curl and save results
$html = curl_exec($ch);
curl_close($ch);
// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);
In $mysrcfile I'll read json data like this (as stated on previous answers):
$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm using PHP to get a JSON response from a website and then process the response using json_decode. This is my PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.checkwx.com/taf/LLBG/?format=json");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'X-API-Key: 555555555'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close ($ch);
$json=json_decode($response,true);
$fulltaf = $json['status']['success']['data']['icao'];
This doesn't work.
This is the JSON data returned to be processed by json_decode:
{
"status": "success",
"data": [
{
"icao": "KPIE",
"observed": "07-03-2017 # 14:20Z",
"raw_text": "KPIE 071353Z 13017G23KT 10SM CLR 21\/13 A3031 RMK AO2 SLP262 T02060128",
"wind_degrees": 130,
}
]
}
You don't specify what didn't work?
First problem is that your JSON has a syntax error. I tried to validate your JSON using http://jsonlint.com and it flagged an extra comma after the 130 for wind_degrees. Check that actual response doesn't have that comma. The JSON won't parse properly with the extra comma.
The next problem is that data is an array (because its data is enclosed in brackets). In this example the array only has one element, [0], therefore to access icao you need to reference it as I show below.
My guess is that the following line didn't work correctly:
$fulltaf = $json['status']['success']['data']['icao'];
Based on the JSON you listed, this line should be the following if you want to retrieve the icao member of data.
$fulltaf = $json['data'][0]['icao'];
The following reference should return 'success' if you want to test for a successful response.
$json['status']
Here is my curl php code:
$ip=$cs[remoteip];
$remoteip = 'http://freegeoip.net/json/'.$ip;
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$remoteip);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$output=curl_exec($ch);
var_dump($output);die();
Here is the response:
string(250) "({"ip":"104.184.193.15","country_code":"US","country_name":"United States","region_code":"FL","region_name":"Florida","city":"Boynton Beach","zip_code":"33472","time_zone":"America/New_York","latitude":26.5253,"longitude":-80.0664,"metro_code":548});"
Now when I do this:
$output=json_decode($output);
curl_close($ch);
var_dump($output);die();
I get a NULL as the response.
I also tried json_decode($output,true) and got NULL as the result:
Not quite sure what to do here.
The json string has a wrong format! The first character '(' and the last two characters ');' should be removed.
I am connecting with an API via curl and POSTing to it.
The API support simply says that I should form my request as so:
"If you send a POST request to the correct URL with a content-type of JSON and a body like what's below you should be off to a good start:
{
"contact": {
"email": "justin#myapi.com",
"last_name": "Johnston",
"company": "MyApi",
"first_name": "Justin"
}
}
However, I think this is for a regular PHP post maybe and not for CURL which is what I am using.
So, the curl code I have is:
//Set Curl options
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "first_name=" . $db->f('fname') . "&last_name=" . $db->f('lname') . "&email=" . $db->f('Email') . "&company=" . $db->f('studio_name') . "");
However, when I run the POST, the response I get back from the API says:
{"error":"Invalid parameters. Should be a hash in the form { 'contact' : { } }."}
So, I am assuming that is because my POSTFIELDS are not correct, and I understand I need to lead with "Contact", but I am not sure how to format it and haven't been able to find an example. Any idears?
Thanks very much for any help you could give! I really do appreciate it!!
Craig
To expand on the comment I posted...
I think the problem is you're sending a string as the parameter, where
it should be a JSON object. just use json_encode() to encode an
array of data and send that via POST instead of the string you're
forming
You need to create a JSON string (usually by encoding an array of data):
$data = array(
"contact" => array(
"first_name" => $db->f('fname'),
"last_name" => $db->f('lname'),
"email" => $db->f('Email'),
"company" => $db->f('studio_name')
)
);
$data = json_encode($data);
This will give you the JSON you need to post, so just change your line of code setting the parameters to this:
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Edit: As requested in a comment, I'll attempt to explain a little more:
The POST request is sent to the server, and you can send any data you want with the request. In the example given in the question, this is valid JSON and they have specified that the body of the request should also be JSON (I'm assuming in the same format):
{
"contact": {
"email": "justin#myapi.com",
"last_name": "Johnston",
"company": "MyApi",
"first_name": "Justin"
}
}
In my solution above I've explained how to get a string containing valid JSON for an array of data; this string can be sent as the contents of the request.
The problem with what you were trying is that the whole data would have literally been sent like this:
first_name=Justin&last_name=Johnston&email=justin#myapi.com&company=MyApi
It's understandable to be confused, as is this is how you would get the data returned from an HTML form, and is quite a common way of sending variables via POST. However in this case you need to use JSON, which is why that won't work.
I tried implementing the following PHP code to POST JSON via PHP: cURL (SOME FORCE.COM WEBSITE is a tag that signifies the URL that I want to POST):
$url = "<SOME FORCE.COM WEBSITE>";
$data =
'application' =>
array
(
'isTest' => FALSE,
key => value,
key => value,
key => value,
...
)
$ch = curl_init($url);
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POST, true);
//Send blindly the json-encoded string.
//The server, IMO, expects the body of the HTTP request to be in JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array
(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string)
)
);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
echo '<pre>';
echo $_POST;
$jsonStr = file_get_contents('php://input'); //read the HTTP body.
var_dump($jsonStr);
var_dump(json_decode($jsonStr));
echo '</pre>';
The output of the above is the following:
"Your TEST POST is correct, please set the isTest (Boolean) attribute on the application to FALSE to actually apply."
Arraystring(0) ""
NULL
OK, the above confirms that I formatted the JSON data correctly by using json_encode, and the SOME FORCE.COM WEBSITE acknowledges that the value of 'isTest' is FALSE. However, I am not getting anything from "var_dump($jsonStr)" or "var_dump(json_decode($jsonStr))". I decided to just ignore that fact and set 'isTest' to FALSE, assuming that I am not getting any JSON data because I set 'isTest' to TRUE, but chaos ensues when I set 'isTest' to FALSE:
[{"message":"System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing body, need at least one of html or plainText: []\n\nClass.careers_RestWebService.sendReceiptEmail: line 165, column 1\nClass.careers_RestWebService.postApplication: line 205, column 1","errorCode":"APEX_ERROR"}]
Arraystring(0) ""
NULL
I still do not get any JSON data, and ultimately, the email was unable to be sent. I believe that the issue is resulting from an empty email body because there is nothing coming from "var_dump($jsonStr)" or "var_dump(json_decode($jsonStr))". Can you help me retrieve the JSON POST? I would really appreciate any hints, suggestions, etc. Thanks.
I solved this question on my own. I was not sure if I was doing this correctly or not, but it turns out that my code was perfect. I kept refreshing my website, from where I am POSTing to SOME FORCE.COM WEBSITE. I believe that the people managing SOME FORCE.COM WEBSITE were having issues on their end. Nothing was wrong with what I did. For some reason, I got a code 202 and some gibberish text to go along with it. I would be glad to show the output, but I do not want to POST again for the sake of the people managing SOME FORCE.COM WEBSITE that I am POSTing to. Thank you guys for your help.