I have this Curl makeup
<?php
$url ="https://min-api.cryptocompare.com/data/price?fsym=USD&tsyms=BTC";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
$json = json_decode($response);
echo $json->BTC;
curl_close($curl);
Trying to get the value of BTC, I got 1.659E-5 instead of 0.00001659. Please I need help on how to decode this without this wrong figure.
PHP automatically uses scientific notation for smaaall numbers display.
You can use (s)printf() to control formatting :
// 8 decimals
printf('%.8f', $json->BTC); // 0.00001654
Related
I want to change the response of an API if an incorrect value is typed..
<?php
if(isset($_GET['q']))
{
$q = ($_GET['q']);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.me.co/bank/resolve?account_number=".$q."&bank_code=".$bcode."",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer demo_03a647487df8a50d343aeb66d2a7305yhfkfllba",
"Cache-Control: no-cache",
),
));
$response = curl_exec($curl);
$err =
curl_error($curl);
curl_close($curl);
}
?>
Now $response is the ouput and irrespective of wat input the user types the $response will ouptut something. If the users input is wrong, it will show a php error which will scare the user.
$q is the users input and have tried using something like
if(!$response)
{
echo "incorrect";
}
The only thing that worked was turning off the error reporting for that page which i do not want cos i dont want the user to proceed.
In summary what i want is to customise the error from $response if the user input is wrong. Thanks as usual.
I'm currently trying to get every title of my JSON decoded output in a variable
This is what works for me as curl
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://api.irail.be/disturbances/?format=json&lang=nl',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'cache-control: no-cache',
'content-type: application/x-www-form-urlencoded'
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
// Decode JSON response and get only the data needed:
$response = json_decode($response);
$response = $response->disturbance[0];
var_dump($response);
$name = $response->title;
echo $name;
When I remove the [0] behind disturbance I am getting a blank $name. Does anyone know how I can fix this?
Thank you
You can access your objects via the keys, but "disturbance" is not a key, it is a value that the key type can take.
You need first to filter your data to get only the items with type = 'disturbance', and then you can get the titles.
Here is an example :
$response = json_decode($response);
$disturbanceItems = array_filter($response, function ($item){return $item->type == 'disturbance';});
echo $disturbanceItems[0]->title ;
Hi im trying to use a custom form on my website to add a new contact to our marketing list, each contact will contain an email and first name.
Im trying to follow this documentation but am having no success:
https://sendgrid.api-docs.io/v3.0/contacts/add-or-update-a-contact
I have tried using their tool but it always says incorrect JSON but when i use an online validator it says correct, I can't figure out how to match theirs to get my request to post.
This is my current code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "{\"list_ids\":[\"bf3ce5bd-14a2-414b-9b81-*****8e8ea62\"],\"contacts\":[{\"email\":\"$email\",\"first_name\":\"$first_name\"]}",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer SG.OCFHb********P3iuikQ.bqKdM-da7X609ZNo9UT7y*********u5fDlfQo80o",
"content-type: application/json"
),
));
You just should be added } chars after $first_name.
This is valid JSON:
CURLOPT_POSTFIELDS => "{\"list_ids\":[\"bf3ce5bd-14a2-414b-9b81-*****8e8ea62\"],\"contacts\":[{\"email\":\"$email\",\"first_name\":\"$first_name\"}]}",
You can check it with https://jsonformatter.curiousconcept.com/ validator website.
One little trick to not have to deal with all the backslashes and escaping is to use a pre-defined object literal in PHP, by using arrays with (object) in front of them, to define the objects nested in the structures.
make an object, turn it into JSON with json_encode
enter the encoded JSON object into the CURLOPT_POSTFIELDS in the cURL request.
<?php
// make custom fields object for entry into the cURL later on:
// THERE IS NO OBJECT LITERAL IN PHP, but using (object) in front of an array, voila
$contact_info = (object)[
"list_ids" => [
"eeee-eeee-eeee-eeee-eeeeexample" // array of list ids here.
],
"contacts" => [ // this is an array of objects (array[object]), according to the api-docs.
(object)[
"email" => "email#example.com",
"country" => "the country",
"city" => "the city",
"custom_fields" => (object)[
"e1_T" => "sign-up-page-name", // only custom fields use ids as the key.
"e2_T" => "next-custom-field" // keep adding custom fields in this array.
]
]
]
];
// now all we have to do is to encode the object into JSON:
$json_contact_data = json_encode($contact_info);
// now add the contact:
$curl = curl_init();
// update the contact
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $json_contact_data, // here we enter the pre-configured json from above.
CURLOPT_HTTPHEADER => array(
"authorization: Bearer " . $your_api_key . "",
"content-type: application/json"
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$decoded = json_decode($response, true); // decode into associative array.
if ($err) {
echo "cURL Error #: " . $err;
} else {
print_r($decoded); // print the decoded json message.
}
?>
This is the best way:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.sendgrid.com/v3/marketing/contacts',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS =>'{"list_ids": ["list-ID"], "contacts": [{"email": "' . $_GET["email"] . '"}]}',
CURLOPT_HTTPHEADER => array(
': ',
'Authorization: Bearer SG.000000000',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
die();
I'm working with a REST API that returns data in paginated format. 1 page will have 100 records. If there is more data there will be a "hasMore" parameter and "offset" parameter defined which you can use to retrieve the next page of results.
So far I've got the following code:
function getData(){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "ENDPOINT",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$data = json_decode($response);
//if there is more get them.....
if($data->hasMore == 1){ //make another request...
while($data->hasMore == 1){
$offset = $data->offset;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "ENDPOINT",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$data = json_decode($response);
$allData = array_merge($data->data, $data->data);
}
}
return $data; //return the results for use
}
My issue is that I'm struggling to have it check if there is more data and if there is request the next page all within the same function. I hope this makes sense and I'd appreciate any help or advice you can offer.
Right now I have it working as I know there is another page. The issue is how can I create it so that it will check the parameter to see if there is more and if there is another page request and append to the existing array of data.
Based on #TommyLee answer, but using the returned offset (just guessing how it is supposed to be used):
function getData($offset = 0){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "ENDPOINT" . "?offset=" . $offset,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$data = json_decode($response);
return $data; //return the results for use
}
$allData = array();
do {
$offset = $data->offset ?: 0;
$data = getData($offset);
foreach($data->data as $row){
$allData[] = $row;
}
} while($data->hasMore == 1);
This way, if nothing is passed to getData(), it assumes the offset is 0, otherwise, you pass it the next offset from the last response.
Again, how the offset is used isn't clear, so you might need to adjust my example to fit the proper usage for $offset.
Your function is fine, but you should really separate the getData function and looping part.
function getData(){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "ENDPOINT",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$data = json_decode($response);
return $data; //return the results for use
}
do{
$data = getData();
$i = 0;
for(i=0; i<data.length; i++){
//do data processing here
}
}while(data->hasMore == 1);
Hey,
i am trying to only show 1 bit of the long string i get from the api i got fram postman, the only thing i need to show is the city. How do i need do this?
i'm trying to find a way with php but i have no clue what to do
a:14:{s:10:"regionName";s:10:"California";s:6:"status";s:7:"success";s:4:"city";s:13:"Mountain View";s:8:"timezone";s:19:"America/Los_Angeles";s:7:"country";s:13:"United States";s:11:"countryCode";s:2:"US";s:3:"zip";s:0:"";s:3:"lon";d:-122.08499908447266;s:3:"isp";s:6:"Google";s:2:"as";s:19:"AS15169 Google Inc.";s:5:"query";s:7:"8.8.8.8";s:6:"region";s:2:"CA";s:3:"lat";d:37.42290115356445;s:3:"org";s:6:"Google";}
(im using the ip of google just for this question)
so the length of the city name changes!
the site where i got it frm http://ip-api.com/php/8.8.8.8
and the code i am using:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://ip-api.com/php/8.8.8.8",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 2e83e542-a6fb-5bb6-94e0-c1908282a2a2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
That's a product of running a PHP variable in a PHP serialize you can reverse it with unserialize
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://ip-api.com/php/8.8.8.8",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 2e83e542-a6fb-5bb6-94e0-c1908282a2a2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
$responseArray = unserialize($response); //You probably need some error trapping here
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $responseArray["country"];
}