PHP Curl Json: multiple outputs - php

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 ;

Related

How to print data in json that has 0 decimal point

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

How to setup correct cURL request for X Post? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have an API to track the shipment, the API request is below and worked well as excepted,
curl -X POST
--header '17token:xxxxxxxxxxxxxxxxxxxxxxxxx'
--header 'Content-Type:application/json'
--data '[{"number":"RR123456789CN"}]'
https://api.17track.net/track/v1/register
Here is my cURL code to get the response.
<?php
// started curl
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.17track.net/track/v1/register",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "number:RR123456789CN", // SOMETHING IS WRONG HERE.
//data '[{"number":"RR123456789CN"}]'
CURLOPT_HTTPHEADER => [
"17token:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"header 'Content-Type:application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
The above code is showing error.
{"code":0,"data":{"errors":[{"code":-18010013,"message":"Submitted data is invalid."}]}}
I have tried all kinds of data structures like :
1. CURLOPT_POSTFIELDS => "RR123456789CN",
2. CURLOPT_POSTFIELDS => "[{number:RR123456789CN}]",
3. CURLOPT_POSTFIELDS => "{number:RR123456789CN}",
4. CURLOPT_POSTFIELDS => '{number:RR123456789CN}',
5. CURLOPT_POSTFIELDS => '{number:RR123456789CN}',
6. CURLOPT_POSTFIELDS => "data '[{number:RR123456789CN}]'",
7. CURLOPT_POSTFIELDS => "{\"number\": \"RR123456789CN\"}",
8. CURLOPT_POSTFIELDS => "[{\"number\": \"RR123456789CN\"}]",
but all the above data structures are failing and showing the same error.
I think I am doing something wrong with X POST / POST or
I am failing to request properly.
Edit
After doing some research I have written new code..
<?php
// setting the main url
$url = 'https://api.17track.net/track/v1/register';
// the tracking id as array
$post_data = array (
'number' => 'RR123456789CN',);
// start
$ch = curl_init();
// URL
curl_setopt($ch, CURLOPT_URL, $url);
// Returntransfer = true
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Post = true
curl_setopt($ch, CURLOPT_POST, 1);
// Header # 1
curl_setopt($ch, CURLOPT_HEADER, "17token:xxxxxxxxxxxxxxxxxxxxxxxxx");
// Header # 2
curl_setopt($ch, CURLOPT_HEADER, 'Content-Type:application/json');
// posting tracking id
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// Getting data in a string ($output)
$output = curl_exec($ch);
// error msg if fails
if ($output === FALSE){
echo "cURL Error:" . curl_error($ch);
}
// turning off the cURL
curl_close($ch);
// Printing the output.
print_r($output);
?>
Now i am getting {"code":401,"data":{"errors":[{"code":-18010002,"message":"Access token is invalid."}]}} error.
Note : Token is valid and correct, i think something is wrong with my code.
Thank you.
You have to send your data as raw body:
$curl = curl_init();
$data = array(0 => array("number" => "CM436202796IN"));
$data = json_encode($data);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.17track.net/track/v1/register',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data, // Mistake is here
CURLOPT_HTTPHEADER => array(
'17token: xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
replace
CURLOPT_CUSTOMREQUEST => "POST",
with just
CURLOPT_POST=>1
and replace
CURLOPT_POSTFIELDS => "number:RR123456789CN", // SOMETHING IS WRONG HERE.
with
CURLOPT_POSTFIELDS => json_encode(array(
0 => array(
"number" => "CM436202796IN"
)
)),
and replace
CURLOPT_HTTPHEADER => [
"17token:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"header 'Content-Type:application/json"
],
with
CURLOPT_HTTPHEADER => [
"17token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Content-Type: application/json"
],

How do i parse a very large json response returned from an API call

I'm accessing data from an API endpoint using curl in my laravel application, which returns a very large JSON response. When I decode this JSON, it appears to decode up to a particular level and stops there. The output is below. You can clearly see that it creates an array and then stops, the rest is an in-iterable string. I wanted to loop over the response, creating a CSV output.
$url = $request->url;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 300000,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
// Set Here Your Requesred Headers
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$data = json_decode($response, true);
dd($data);
JsonToCsv::exportCSV($data);
Please how do I properly parse this large JSON response?
Thank you in advance

Why am i having issues with this curl?

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.

PHP pull and display values from API url

If I use the following:
$homepage = file_get_contents('http://www.website.com/api/v1/members/102210');
echo $homepage;
The data is displayed as follows:
{"user":{"profile":{"Id":{"Label":"User Id","Value":102210},"User":{"Label":"User Name","Value":"tom"}
I tried the following that I discovered on here in another post but the page remains blank other than User:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://www.website.com/api/v1/members/102210",
CURLOPT_RETURNTRANSFER => true,
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);
$err = curl_error($curl);
curl_close($curl);
$response = json_decode($response, true); //because of true, it's in an array
echo 'User: '. $response['User']['User Name'];
You're misinterpreting the JSON data. There is no User key in the root of the json object and there is no User Name key inside of that either. When you visualize the JSON, this is what it looks like:
What you seem to be looking for is:
echo 'User: ' . $response['user']['profile']['User']['Value'];
I'm not sure why you'd switch to cURL if the file_get_content method works for you. You should be able to simply do this:
$homepage = file_get_contents('http://www.website.com/api/v1/members/102210');
$response = json_decode($homepage, true);
echo 'User: ' . $response['user']['profile']['User']['Value'];

Categories