Post json object with php(http post)? - php

I need to post json object with http post request and to handle responses.
json object :
{
"my_json" : "12345"
}
I wrote somethinh like this,but this don't work.
$url = "http://localhost/my_json.json";
$json_Data = file_get_contents($url,0,null,null);
print_r($json_Data);
And it doesn't print anything.
Help please.

Client:
<?php
$data = array('foo' => 'bar', 'red' => 'blue');
$ch = curl_init();
$post_values = array( 'json_data' => json_encode( $data ) );
curl_setopt($ch, CURLOPT_URL, 'http://localhost/server.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_values);
$data = curl_exec($ch);
if(!curl_errno($ch))
{
echo 'Received raw data' . $data;
}
curl_close($ch);
?>
Server (server.php):
<?php
$data = json_decode( $_POST['json_data'] );
// ... do something ...
header('Content-type: text/json');
print json_encode($response);
?>

$url = "http://localhost/my_json.json";
$json_Data = file_get_contents($url,0,null,null);
$new = json_decode($json_Data);
print_r($new);
I think that might do it

Try this:
$jsonFile = 'http://localhost/my_json.json';
$jsonData = file_get_contents($jsonFile);
$phpData = json_decode($jsonData);
print_r($phpData);

The problem may be from the file_get_contents extraneous arguments :
The 2d arg should be a boolean and is optional (default value is false)
The 3rd arg is ok
The 4th should be an integer, is optional (default value is -1)
So you should try $json_Data = file_get_contents($url);
Furthermore to view the data in your browser you should try with header('Content-type: text/plain'); just before outputting with print_r() so that no processing will be made by your browser
To be sure there is really nothing sent to your browser, you may also try FireFox + FireBug to see HTTP replies...

Related

Is there a way to get value of json object from a URL in PHP?

So i am trying to get values of json object from a url, when i hit that url on post man i get something like this
{
"error": "0",
"errorString": "",
"reply": {
"nonce": "5e415334832a8",
"realm": "VMS"
}
}
So, i am trying to write a php code that displays the value of nonce in the browser but it is not working
i have the following code
$getNonceUrl = "https://example.com/api/getNonce";
$getContect = file_get_contents($getNonceUrl);
$jsonNoce = json_decode($getContect, true);
$dd = $jsonNoce->reply[0]->nonce;
echo $dd;
I also did this
$ch = curl_init("https://example.com/api/getNonce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
echo $ch->reply[0]->nonce;
But it does not seem to work still.
Below your 2 code samples with suggested corrections.
Using file_get_contents : remove 2nd argument of json_decode
$getNonceUrl = "https://example.com/api/getNonce";
$getContect = file_get_contents($getNonceUrl);
$jsonNoce = json_decode($getContect); // note removal of 2nd parameter
$dd = $jsonNoce->reply[0]->nonce;
echo $dd;
Using curl : you forgot to parse curl output with json_decode
$ch = curl_init("https://example.com/api/getNonce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data); // added this line, because curl doesn't decode json automatically
echo $ch->reply[0]->nonce;

How to return an object and not a string with PHP curl request

I am attempting to request data from a url and am having success for most endpoints except for one. Throughout my troubleshooting, I can retrieve the text and display it in the browser, however, when I try to store it as an object, I get nothing. It actually still stores as a string. I would like to iterate through the object so that I can run calculations on the contents.
Is it because the JSON string is malformed? If so, how do I correct? I have tried a variety of solutions with no success.
Important to note that gzip is required, for that reason I have included 'ob_gzhandler'. the contents only echos when I use gzhandler.
THE ECHOS IN THE FUNCTION ARE FOR TROUBLESHOOTING PURPOSES. THEY ILLUSTRATE WHERE STRINGS ARE BEING PRODUCED AND NOT OBJECTS.
function CallAPI_oanda_v20($instruments)
{
$curl = curl_init();
$url = 'https://api-fxtrade.oanda.com/v3/instruments/'.$instruments.'/positionBook';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPGET,TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: <USE MY API KEY>'));
$response = curl_exec($ch);
echo gettype($response); //returns "string"
$json = json_decode($response, true);
echo gettype($json); //returns "NULL"
curl_close($ch);
return $json;
}
$call = CallAPI_oanda_v20("GBP_USD");
ob_start('ob_gzhandler');
//$output = ob_get_contents();
echo $call->positionBook; //returns an error:Trying to get property 'positionBook' of non-object
echo gettype($output); //THIS WILL RETURN "string".
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($output, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
In order to troubleshoot that the call is correct, I echo the contents by graying out the following line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
Here is the json string that prints:
{"positionBook":{"instrument":"GBP_USD","time":"2019-09-02T00:00:00Z","unixTime":"1567382400","price":"1.21584","bucketWidth":"0.00050","buckets":[{"price":"1.19950","longCountPercent":"0.0189","shortCountPercent":"0.0189"},{"price":"1.20000","longCountPercent":"0.0000","shortCountPercent":"0.0189"},{"price":"1.20100","longCountPercent":"0.0000","shortCountPercent":"0.0189"},{"price":"1.20150","longCountPercent":"0.0000","shortCountPercent":"0.0757"}]}}
ob_start('ob_gzhandler');
$output = ob_get_contents();
echo gettype($output); //THIS WILL RETURN "string".
This is exactly what you expect. The output buffer is just a big string that is appended to whenever you write to it. When you gettype($output) you're just getting the output of that buffer, which is nothing to do with any of your other code.
As you're not actually writing anything to said buffer, it will be an empty string.
You're not actually using the result of your function ($call) anywhere. You should be passing it to your recursive array iterator. In your top function you probably want to add TRUE as the second argument to json_decode so it's fully array based.
SOLVED. I was improperly decoding the gzip string.
$response = gzdecode($response);
This was the key, along with removing:
ob_start('ob_gzhandler');
$output = ob_get_contents();
Here is the solved piece of code:
{
$curl = curl_init();
$url = 'https://api-fxtrade.oanda.com/v3/instruments/'.$instruments.'/positionBook';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPGET,TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: <USE MY API KEY>'));
$response = curl_exec($ch);
$response = gzdecode($response);
$json = json_decode($response, true);
curl_close($ch);
return $json;
}
$call = CallAPI_oanda_v20("GBP_USD");
echo '<pre>';
print_r($call);
echo '<pre>';```

Print JSON data from currencyconverterapi

I'm trying to print the value from currency converter API JSON data.
Anyone can help me to print the value from this URL
https://free.currencyconverterapi.com/api/v5/convert?q=USD_IDR&compact=y?
You have to use file_get_contents() along with json_decode()
<?php
$json_data = file_get_contents('https://free.currencyconverterapi.com/api/v5/convert?q=USD_IDR&compact=y');
$array = json_decode($json_data, true);
var_dump($array["USD_IDR"]["val"]);
?>
I have tested it on the local machine and working fine:-
https://prnt.sc/jd1kxo And https://prnt.sc/jd1l7w
Use Json_decode
$data = json_decode('{"USD_IDR":{"val":13965}}', TRUE);
var_dump($data["USD_IDR"]["val"]); //int(13965)
Try this:
ob_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://free.currencyconverterapi.com/api/v5/convert?q=USD_IDR&compact=y');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$jsontoarr = json_decode($response);
echo $jsontoarr->USD_IDR->val;
Good luck.

PHP struggling to decode JSON

I have script that calls at script via cURL. It looks like this,
Route::get('login-redirect', function() {
if (Input::has('error')) {
return Input::get('error_description');
}
if (Input::has('code')) {
$fields = array(
'grant_type' => 'password',
'username' => 'admin#local.com',
'password' => 'passwohrd',
'client_id' => 'testclient'
);
$fieldstring = http_build_query($fields, "\n");
$url = "http://apitest.local/api/v1/get-token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldstring);
$result = curl_exec($ch);
$json = json_decode($result);
curl_close($ch);
$fields = array('access_token' => '3c1e6b099f172fc01304403939edf8e56904ab61');
$fieldstring = http_build_query($fields, "\n");
$url = "http://apitest.local/api/v1/me";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldstring);
$result = curl_exec($ch);
curl_close($ch);
dd($result);
}
The json returned looks like this, if I do dd($json)
{"content":null,"error":true,"error_description":"Invalid username and password combination"}int(1)
I feel like after running it through json_decode I should be able to just output $json->error but no.
The JSON gets made in the following class, but I cannot see anything odd here either, I am doing incorrect, or do I misunderstand json_decode?
<?php
namespace Shaunpersad\ApiFoundation\Http;
use App;
use Response;
class ErrorResponse
{
public static function make($message = '', $status = 200, array $headers = array(), $options = 0)
{
$response = App::make(
'api_response_array',
array(
'content' => null,
'error' => true,
'error_description' => $message
)
);
return Response::json($response, $status, $headers, $options);
}
}
First of all, you do not have CURLOPT_RETURNTRANSFER - your curl_exec returns output buffer directly to the screen.
Second of all, it looks like you have var_dump somewhere and I cannot see where :)
Third of all - you didn't asked any direct question.
Edit
Okay i've read it few time and answer below. The dd() function is truly a var_dump wrapper but it is dumping var_dump data into json format afaics.
What you've got as an output is not from dd($json):
// this part has been output by curl_exec():
{"content":null,"error":true,"error_description":"Invalid username and password combination"}
// only this part comes from dd($json):
int(1)
Here's why:
// no CURLOPT_RETURNTRANSFER, so curl_exec() outputs result and returns true:
$result = curl_exec($ch);
// thus $result = true;
// so here $json = 1, since this is what json_decode(true) will return
$json = json_decode($result);
// then you did dd($json), so it just appended var_dump(1) to the output:
{"content":null,"error":true,"error_description":"Invalid username and password combination"}int(1)
Update
As stated in the other answers, you're not actually receiving the output because you haven't set CURLOPT_RETURNTRANSFER. So curl_exec() will echo out the response to the DOM and return true (1) as your curl request ran successfully.
You'll be able to run the below stuff by setting this in your curl request somewhere:
curl_setop(CURLOPT_RETURNTRANSFER, true);
dd() is a laravel function and this is what the documentation says:
Dump the given variable and end execution of the script.
I'd presume it is just a wrapper function for a prettier looking var_dump() (As I don't use laravel, I wouldn't know its exact output.).
What you want is to decode the $result that is returned from your cUrl. Something like this should suffice:
$data = json_decode($result);
echo $data->error_description;
The successfully decoded object looks like this:
stdClass Object
(
[content] =>
[error] => 1
[error_description] => Invalid username and password combination
)
Example
You can even test your boolean error value like this now:
if($data->error) {
//....true
} else {
//....false
}

Is it possible to return data with post method in curl

I am trying to learn curl with php. I know it is possible to send values to another script with post method using curl. But if I want that, after first time sending that values executes there and return again with post method .... is that possible.
Here on my two script:
Index.php
<?php
$url = 'http://localhost/curl/test.php';
$post_data = array(
'first' => '1',
'second' => '2',
'third' => '3'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
?>
and test.php
<?php
$a = $_POST['first'];
$b = $_POST['second'];
$c = $a+$b;
$d = $b-$a;
$e = $a*$b;
$output = array(
'choose' => $c,
'choose1' => $d,
'choose2' => $e
);
print_r($output);
?>
Here index.php send via post method and I can access that with $_POST['first']. If I want that I transfer $output array from here test.php and can access them as $_POST['choose'] from index.php, is that possible?
The response from curl will not automattically populate superglobals like $_POST as these are set at script load.
You will need to parse the curl response yourself. I suggest you return it in a format that is easily parseable by PHP. For example, JSON using json_decode().
Example
Replace your print_r() with the following code, respectively.
test.php
echo json_encode($output);
index.php
$data = json_decode($output, true);
print_r($data);
Instead of print_r($output); create a function module in test.php handling the data, and returning:
return $output;
index.php, $output = curl_exec($ch); is correct, you can eventually access the data in the following way:
echo $output->choose;
echo $output->choose1;
or use the parse_str() or json_decode() as Jason mentioned above.

Categories