Retrieve Json Data Using CURL PHP - php

Using CURL here we retrieve data and print then save to file after that insert it into database.
$curl = curl_init();
$options=array(
CURLOPT_URL=>"http://api.abc.com/v1/products/search.json?q=ball",
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_ENCODING =>"",
CURLOPT_FOLLOWLOCATION =>true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT=>30,
CURLOPT_HTTP_VERSION=>CURL_HTTP_VERSION_1_0,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS=>"",
CURLOPT_HTTPHEADER=> array(
"authorization: AsiMemberAuth client_id=50041351&client_secret=55700485cc39f1",
"cache-control: no-cache"
),
CURLOPT_HEADER=> true
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err){
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The Result json is fine. now i want to save it in json file?

to save a string to a file in php, you can use file_put_contents()
file_put_contents doc
file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int
You can update your code as follows:
if ($err){
echo "cURL Error #:" . $err;
} else {
echo $response;
//Write response to file
file_put_contents("my_file.json", $response)
}

Related

Extracting json string with PHP

JSON string that i received from the API
{"accessTokenResponse":{"token":"562371e99fda4296a380547cb5bf9fab","token_type":"Bearer","expires_in_seconds":"77476","client_id":"LTcyMDI1NDI0OQ==","responseStatus":{"code":"100000","message":"Service operation completed successfully","messageDetails":"Access token assigned."}}}
Information that i wanted to extract
562371e99fda4296a380547cb5bf9fab //-->The Token
My attempt
<?php
$user = "LTcyMDI1NDI0OQ==";
$password = "MjAzMDI5MTU";
$returnFormat = "json";
$url = "https://sandbox.dhlecommerce.asia/rest/v1/OAuth/AccessToken?clientId=".$user.
"&password=".$password."&returnFormat=".$returnFormat."";
$method = "GET";
$headers = array(
"content-type: application/json",
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
));
$response = curl_exec($curl);
$err = curl_error($curl);
$result = json_decode($response);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $result->token;
}
?>
The output:
Warning: Undefined property: stdClass::$token in C:\xampp\htdocs\Tracking\getToken.php on line 31
Did the JSON string that i received is in bad format?
Why does it says undefined property? Appreciate any helps. thanks!
Post that i've refer to:
How do I extract data from JSON with PHP?
token is in the accessTokenResponse object, so :
echo $result->accessTokenResponse->token;

Download Github Release asset file via PHP

I am using PHP Github API to list my releases. Now I need to copy an asset file to my server from the latest release.
The PHP Github API does not provide download functionality so I decided to make a cURL request directly.
This is my code atm:
<pre>
<?php
// This file is generated by Composer
require_once '../vendor/autoload.php';
$client = new \Github\Client();
$client->authenticate(':mytoken', null, Github\Client::AUTH_ACCESS_TOKEN);
$release = $client->api('repo')->releases()->latest('arminetsw', 'webstore');
$nombre_fichero = $release['assets'][0]['name'];
$download_url = $release['assets'][0]['browser_download_url'];
$download_url = 'https://api.github.com/repos/arminetsw/webstore/releases/assets/:myAssetId?access_token=:mytoken';
$cliente = curl_init();
$file = fopen("webstore.zip", 'w');
curl_setopt($cliente, CURLOPT_URL, "https://api.github.com/repos/arminetsw/webstore/releases/assets/32188729?access_token=:mytoken");
curl_setopt($cliente, CURLOPT_HEADER, 'Accept: application/octet-stream');
curl_setopt($cliente, CURLOPT_USERAGENT, 'Webstore');
curl_exec($cliente);
curl_close($cliente);
fclose($file);
//$nuevo_fichero = ''
/*if (!copy($download_url, $nombre_fichero)) {
echo "Error al copiar $nombre_fichero...\n";
}*/
var_dump($release);
?>
</pre>
I only get a webstore.zip 0 bytes file with no errors.
*The repo is private.
Final working code:
<pre>
<?php
set_time_limit(0);
require_once '../vendor/autoload.php';
$client = new \Github\Client();
$client->authenticate('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', null, Github\Client::AUTH_ACCESS_TOKEN);
$release = $client->api('repo')->releases()->latest('user', 'repo');
$nombre_fichero = $release['assets'][0]['name'];
$download_url = $release['assets'][0]['url'];
$authorization = "access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$download_url .= "?" . $authorization;
$file = fopen($nombre_fichero, 'w');
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $download_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_USERAGENT => "Webstore",
CURLOPT_FILE => $file,
CURLOPT_HTTPHEADER => [
"Accept: application/octet-stream",
"Content-Type: application/octet-stream"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
fputs($file, $response);
fclose($file);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
</pre>

Type of 'json' response is boolean in PHP

I am using the following:
<?php
$url = '...';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => "GET"
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = json_decode($response, true);
echo gettype($response); /$response/ THIS RETURNS INTEGER FOR SOME REASON!
?>
So the $response I am getting is of type integer, and I am unable to read the elements of this JSON.
Also note that when I echo the response, 1 is printed after it.
Check the manual for the possible return values. You need to at least use CURLOPT_RETURNTRANSFER.
Returns TRUE on success or FALSE on failure. However, if the
CURLOPT_RETURNTRANSFER option is set, it will return the result on
success, FALSE on failure.
<?php
$url = '...';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true // <<<< add this
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
var_dump(json_last_error_msg());
}
'$result' is not defined in your code, double check it?
Perhaps the line "$response = json_decode($response, true);" needs to be changed.
A default value for undefined variable is NULL/False

How to turn API response into an image?

I'm trying to work with an API using Postman. In Postman the image displays fine. I am using Postman to generate the following code
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.com/v2/tier1/XXXXX/photos/photo/MYPHOTOIDISHERE/download?api_key=MYAPIKEYISHERE",
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: 74f19da6-d4ba-fe02-4ad3-2a313b472ca2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The only modification I have made to the code from Postman is the CURLOPT_SSL_VERIFYPEER as I was getting an error.
The image displays perfectly in Postman but when I try to use the code myself I get a long string that looks like UTF. A small sample (it's very long) of this is as follows;
����JFIF``��C #!!!$'$ & ! ��C ����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�
How do I convert this into an image?
The result you are seeing is the actual bytes of the image.
You need to save that to a file or process it as image bytes. To save it, dump it to a file using file_put_contents($filename, $data)
// Instead of 'echo $response';
file_put_contents('image.jpg', $response);
You will see a new file image.jpg in your script's directory.
This assumes the image is a jpeg, you could do some checks to determine the type before saving it.
I am able to save image in folder, but problem is that Its showing error - window photo viewer can't open this picture because the file appears to be damaged, corrupted or is too large
here is my code
$oAuthToken = $token->access_token;
$getUrl = 'https://www.googleapis.com/drive/v2/files/' . $googlefileid . '?alt=media';
$authHeader = 'Authorization: Bearer ' . $oAuthToken ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
$authHeader ,
]);
$data = curl_exec($ch);
curl_close($ch);
Storage::put($googlfilename,$data);
Please tell me what i am doing wrong.

Call online-convert rest api

I'm using this service online-convert trying to make a simple call like in the online-convert sample. However they do not have examples of actual code so I'm kinda in the dark. online-convert docs
I have got that far, here is my best guess at what a call should look like:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api2.online-convert.com/jobs");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Host: https://api2.online-convert.com",
"X-Oc-Api-Key: <my api key>",
"Content-Type: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
Any help will be appreciated.
They are using a REST API to convert files. Here is an example.
First create a json file with a link where the file you want to convert can be downloaded (uploads are handled differently). Also add the format you want to convert to. Save it as test.json.
{
"input": [{
"type": "remote",
"source": "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png"
}],
"conversion": [{
"category": "image",
"target": "png"
}]
}
Then send this file using curl to the API of online-convert.com. Add your API key to the script below and save it as start.php in the same directory where you saved the test.json:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api2.online-convert.com/jobs",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => file_get_contents('test.json'),
CURLOPT_HTTPHEADER => array(
"content-type: application/json",
"x-oc-api-key: <your API key here>"
),
)
);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
Execute the PHP file on the command line with
php save.php
You can also call the script using a webbrowser.
After you have successfully sent the job and got a valid response, you can obtain the status of the conversion. For this you need the id (job id) you got in the answer when executing start.php. Create a file called status.php and execute it.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api2.online-convert.com/jobs/<your job id here>",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"content-type: application/json",
"x-oc-api-key: <your API key here>
),
)
);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
There you will find the URL to download your file.
The API is much more powerful than that. You can upload files you want to convert, create multiple conversions of one single file (e.g. videos in different resolution with one API call) and set various conversion options.

Categories