Print values in REST API - php

The HTTP Rest API shows me the values above :
id 514
filial 5
name "COD. 514 20 Mb RES. TRL"
nome_amigavel "20 Mb"
mensalidade "89.90"
desconto "0.00"
ativo 1
tipo 1
instalacao "300.00"
bnd_up 2000
bnd_down 20000
1
id 422
filial 4
name "COD. 069 30 Mb TRANSPORTE"
nome_amigavel "30 Mb"
mensalidade "1500.00"
desconto "0.00"
ativo 1
tipo 3
instalacao "1500.00"
bnd_up 0
bnd_down 30000
2
How Can I "print" or "Echo" a specific value or a single value in a PHP file ????
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://services.west.net.br/rest/server.php/planos",
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: Basic YXaBepOmsadsahpaacGVwwaybassdwsadsadsawd3BpYSBw0cmddF2YWdaalbSBiaXBdlbmFkbw==",
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
Im try this , but no sucess , im newbiee in rest api , and try some examples from the web, please help with some!!!

with the code below
$curl_response = curl_exec($curl); //<!---- $curl_responce instead of $output
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' .
var_export($info)); //<!--- this is pointless IMO
}
curl_close($curl);
$decoded = json_decode($curl_response); ///<!--- set to results to $decoded, also no second value ie. "json_decode($curl_response, 1);"
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
//==================================//
// looks like someone just dropped the code below
// this line in. ha ha.
$result = json_decode($output, 1); //<!--- output does not exist, but this is already done above. so use $decoded instead of $output.
// check if an id came back
if (!empty($result['id'])) {
$deal_id = $result['id'];
return $deal_id;
} else {
return false;
}
echo $deal_id;
the variable $output is never set, instead use $decoded. This is because $result also does not exist and is instead $curl_response in your code above. Sense you already have it decoded, there is no need to decode it again.
That said, in the json_decode there, the second parameter is not set to true, when that is the case you get an object back and not an array as you might expect.
http://php.net/manual/en/function.json-decode.php
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
assoc
When TRUE, returned objects will be converted into associative arrays.
The second option is JSON_OBJECT_AS_ARRAY that has the same effect as setting assoc to TRUE.
To fix the part your having trouble with you should be able to replace the stuff below the ===== with this.
// check if an id came back
if (!empty($output->id)) {
$deal_id = $output->id;
return $deal_id;
} else {
return false; // should echo something instead of returning.
}
echo $deal_id;
Also to remove the other output, comment these 2 lines.
echo 'response ok!';
var_export($decoded->response);

Related

Interrogate API until no results left

I am working with an API at the moment that will only return 200 results at a time, so I am trying to run some code that works out if there is more data to fetch based on whether or not the results have a offsetCursor param in them as this tells me that that there are more results to get, this offsetCursor is then sent a param in the next request, the next set of results come back and if there is an offsetCursor param then we make another request.
What I am wanting to do is push the results of each request into a an array, here is my attempt,
function get_cars($url, $token)
{
$cars = [];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
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(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err) {
return false;
} else {
$results = json_decode($response, TRUE);
//die(print_r($results));
$cars[] = $results['_embedded']['results'];
if(isset($results['cursorOffset']))
{
//die($url.'&cursor_offset='.$results['cursorOffset']);
get_cars('https://abcdefg.co.uk/service/search1/advert?size=5&cursor_offset='.$results['cursorOffset'], $token);
//array_push($cars, $results['_embedded']['results']);
}
}
die(print_r($cars));
}
I assume I am doing the polling of the api correct in so mush as that if there is a cursor offet then I just call the function from within itself? But I am struggling to create an array from the results that isnt just an array within and array like this,
[
[result from call],
[resul from call 2]
]
what I really want is result from call1 right through to call n be all within the same sequential array.
using a do+while loop, you'll have only 1 instance of cars variable, that would work.
Since you're using recursion, when you call get_cars inside get_cars, you have 2 instances of cars variable, one per get_cars call.
IMHO, using a loop is better in your case.
But if you still want to use recursion, you should use the result of get_cars call, something like this:
if(isset($results['cursorOffset']))
{
//die($url.'&cursor_offset='.$results['cursorOffset']);
$newcars = get_cars('https://abcdefg.co.uk/service/search1/advert?size=5&cursor_offset='.$results['cursorOffset'], $token);
$cars = array_merge($cars, $newcars);
//array_push($cars, $results['_embedded']['results']);
}
(and get_cars should return $cars, instead of printing it with print_r)
Edit: here is an example of, untested, code with a while loop (no need for do+while here)
<?php
function get_cars($baseUrl, $token)
{
$cars = [];
// set default url to call (1st call)
$url = $baseUrl;
while (!empty($url))
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
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(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err)
{
// it was "return false" in your code
// what if it's the 3rd call that fails ?
// - "return $cars" will return cars from call 1 and 2 (which are OK)
// - "return false" will return no car (but call 1 and 2 were OK !!)
return $cars;
}
$results = json_decode($response, TRUE);
$cars[] = $results['_embedded']['results'];
if(isset($results['cursorOffset']))
{
// next call will be using this url
$url = $baseUrl . '&cursor_offset='.$results['cursorOffset'];
// DONT DO THE FOLLOWING (concatenating with $url, $url = $url . 'xxx')
// you will end up with url like 'http://example.com/path/to/service?cursor_offset=xxx&cursor_offset==yyy&cursor_offset==zzz'
// $url = $url . '&cursor_offset='.$results['cursorOffset'];
}
else
{
$url = null;
}
}
return $cars;
}

cannot access php json decoded multi dimensional array values curl

when i execute the below code to access koinex ticker api , I am getting an array but how can i display only certain values :
echo $response[0][0][1];
echo $response['prices']['BTC'][0];
code :
<?php
$getCurrency = "inr";
$displayArrayOutput = true;
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://koinex.in/api/ticker',
CURLOPT_USERAGENT => 'Something here'
));
// Send the request & save response to $resp
$response = curl_exec($curl);
// Close request to clear up some resources
$err = curl_error($curl);
curl_close($curl);
if ($err) {
} else {
if($displayArrayOutput){
$response = json_decode($response, true);
print_r($response);
}
else{
header("Content-type:application/json");
echo 'touine';
}
}
echo $response[0][0][1];
echo $response['prices']['BTC'][0];
?>
sorry a little new to php , open to any other kind of approach for decoding json

Reading Json Curl content results in php

I have a json output below that am trying to get its contents
{"content":"people",
"nextLink":"https://example.com/people?$skip=3",
"value":[
{
"id":"100","displayName":"Room Rainier",
"Addresses":[{"location":"12 orlando street","Spore":8.0}],
"phones":[{"type":"home","number":"10000000000"}],
"personType":{"class":"new","subclass":"Room1"}
},
{
"id":"102","displayName":"Tony Blur",
"Addresses":[{"location":"19 saco street","Spore":4.0}],
"phones":[{"type":"business","number":"1080000000"}],
"personType":{"class":"Other","subclass":"Room2"}
},
{
"id":"103","displayName":"veronica huges",
"Addresses":[{"location":"6 nano street","Spore":7.0}],
"phones":[{"type":"business","number":"111000000"}],
"personType":{"class":"old","subclass":"Room5"}
}]}
Below is my working Json Curl in PHP
<?php
session_start();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://example.com/people",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//CURLOPT_CUSTOMREQUEST => "GET",
//CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer --my bearer goes here--"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$res=json_decode($response);
$res1=json_decode($response, true);
$js = json_decode($response, true);
echo '<pre>' . print_r($response, true) . '</pre>';
$re = $js['value'];
foreach ($re as $value1) {
echo $value1['id'];
echo '<br>';
echo $value1['Addresses']['location'];
echo '<br>';
echo $value1['phones']['type'];
echo '<br>';
}
if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
}
?>
my success
I was able to get all values for id **(echo $value1['id'])** in for each loops.
my Problem
1.) I cannot get values for Addresses Locations **(echo $value1['Addresses']['location'])** and phones Types **(echo $value1['phones']['type'])** in for each loop respectively as it shows nothing.
2.) The json file has a next link options hence
"nextLink":"https://example.com/people?$skip=3"
how can I display more users/peoples data based on the link. Thanks
The Addresses and Phones are Arrays so if you want to get the first you can use index 0 or you can get all with loop in case there is more than 1 address or phone.
foreach ($re as $value1) {
/**
* To get the first address and phone use index 0
*/
echo $value1['Addresses'][0]['location'];
echo $value1['phones'][0]['type'];
/**
* Loop to get all addresses and phones
*/
foreach($value1['Addresses'] as $address) {
echo $address['location'];
}
foreach($value1['phones'] as $phone) {
echo $phone['type'];
}
}
If there is a next link you should request the nextLink just use curl again with the next link.
It will be easier if you create a function for this and just call the function again with the next link.

Cannot get PHP function to re-run and update array

My PHP code looks something like this:
$size=1;
$newoffset=0;
$final=[];
function runQuery()
{
global $newoffset;
global $size;
global $final;
$SECRET_KEY = 'XXX';
$s = hash_hmac('sha256','/api/v2/tags?limit=100&offset='.$newoffset.'-', $SECRET_KEY, false);
$curl = curl_init();
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = "RT-ORG-APP-CLIENT-ID: XXX";
$headers[] = "RT-ORG-APP-HMAC: ". $s;
curl_setopt_array($curl, array(
CURLOPT_URL => 'api/v2/tags?limit=100&offset='.$newoffset,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$array = json_decode( $response, true );
$results = $array['data'];
//print_r($results); This returns correctly
$size = sizeof($array['data']); //size of array
$result = array();
if ($size>0){
//print_r($results); This also returns correctly
$newoffset += 100;
foreach($results as $member) {
$result[] = array(
'tag_name' => $member['name'],
'tag_id' => $member['id'],
'tag_public_id' => $member['public_id'],
);
}
$final['all_tags'] = $result;
}
}
}//end function
if($size>0){
runQuery();
}else{
echo json_encode($final);
}
What this is supposed to do is run the curl and if it returns results then push those results into $final. If there are results, then increase the value of a variable (newoffset) so that it can be used in the curl request. This is because I can only get 100 results at a time and need to do offset as many times as necessary to get them all.
If the size of what's returned is 0, then stop and echo the results.
However, this returns nothing.
I'm thinking I have a global variable problem.
Note that I know the query works if I remove all the conditionals and functions, so that isn't the issue.
Any suggestions on how to fix?
Your runQuery function is running only once because you're calling it only once. Execution does not continue at the line where the function declaration ends, it continues where the function was called, which in your case is the end of your script.
You'll have to move the
if($size>0){
runQuery();
}else{
echo json_encode($final);
}
part into the function and just call runQuery once.
Also, using global variables is discouraged because it could lead to clashes with other code. It's better to use function parameters and return values.

How to encode plain text response to JSON and take specific Data using PHP CURL

I am getting api response in plain text format. So operation with response data I need to encode the response into JSON format. Then I can easily grab the desire response data and use it.
Request CODE(Sample) ::
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://api.arshohag.me/test",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "login=testapp&key=152456&md5=chasdg4as432&action=test",
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);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Response CODE(Sample) ::
id=2566546
authentication_key=74448975
error_code=0
error_txt=Test Ok
I want to encode The response is in JSON format like this -
{
"id" : "2566546",
"authentication_key" : "74448975",
"error_code" : "0",
"error_txt" : "Test Ok"
}
and also grab the data like this -
$id=array["id"];
echo $id;
$rawText = "
id=2566546
authentication_key=74448975
error_code=0
error_txt=Test Ok
";
// Split by new line
// array_filter to skip empty values
$linesArray = array_filter(preg_split('/\R/', $rawText));
$craftedArray = array();
foreach($linesArray as $line) {
$tempArray = explode("=", $line);
$craftedArray[$tempArray[0]] = $tempArray[1];
}
// Encode to JSON Object
echo json_encode($craftedArray);
Output:
{
id: "2566546",
authentication_key: "74448975",
error_code: "0",
error_txt: "Test Ok"
}
To get data back from JSON:
// Decode JSON. Assume JSON object is stored in $jsonData
$decodedData = json_decode($jsonData);
var_dump($decodedData);
// Access like below
$id = $decodedData->id;
echo "\nID is: ".$id;
Output:
object(stdClass)#1 (4) {
["id"]=>
string(7) "2566546"
["authentication_key"]=>
string(8) "74448975"
["error_code"]=>
string(1) "0"
["error_txt"]=>
string(7) "Test Ok"
}
ID is: 2566546
Do it by json_encode. Use it like this
var_dump(json_decode($response, true));
Reference http://php.net/manual/en/function.json-encode.php
This method works for Java, you can convert it to your language if each line ends with \r\n
String jsonStringConverter(String stringResponse) {
String[] parts = stringResponse.split("\\r\\n");
String jsonString = "{\"";
for (int i = 0; i < parts.length; i++) {
jsonString += parts[i].replace("=", "\":\"");
jsonString += (i < parts.length - 1) ? "\", \"" : "";
}
return jsonString += "\"}";
}

Categories