Reading Json Curl content results in php - 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.

Related

Grab the race number from a tracking software

I want to grab this number (28/28) with PHP from a tracking software (https://aircrasher.livefpv.com/live/scoring/) for drone races. But I can't. I think it's a websocket, but I don't know how to retrieve information from it. I tried curl, I tried the "ultimate-web-scraper" from GitHub (https://github.com/cubiclesoft/ultimate-web-scraper). I tried a code example from another post from here (PHP simple web socket client) but I'm not able to get this number. Is it imposible to get this number (with php)?
This is what I tried so far with the help of "ultimate-web-scraper" (https://kleesit.de/beta/livetime/webscraper/test.php):
<?php
require_once "support/web_browser.php";
require_once "support/tag_filter.php";
// Retrieve the standard HTML parsing array for later use.
$htmloptions = TagFilter::GetHTMLOptions();
// Retrieve a URL (emulating Firefox by default).
$url = "https://aircrasher.livefpv.com/live/scoring/";
$web = new WebBrowser();
$result = $web->Process($url);
// Check for connectivity and response errors.
if (!$result["success"])
{
echo "Error retrieving URL. " . $result["error"] . "\n";
exit();
}
if ($result["response"]["code"] != 200)
{
echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
exit();
}
// Get the final URL after redirects.
$baseurl = $result["url"];
// Use TagFilter to parse the content.
$html = TagFilter::Explode($result["body"], $htmloptions);
// Find all anchor tags inside a div with a specific class.
// A useful CSS selector cheat sheet: https://gist.github.com/magicznyleszek/809a69dd05e1d5f12d01
echo "All the URLs:\n";
$result2 = $html->Find("div.someclass a[href]");
if (!$result2["success"])
{
echo "Error parsing/finding URLs. " . $result2["error"] . "\n";
exit();
}
foreach ($result2["ids"] as $id)
{
// Faster direct access.
echo "\t" . $html->nodes[$id]["attrs"]["href"] . "\n";
echo "\t" . HTTP::ConvertRelativeToAbsoluteURL($baseurl, $html->nodes[$id]["attrs"]["href"]) . "\n";
}
// Find all table rows that have 'th' tags.
// The 'tr' tag IDs are returned.
$result2 = $html->Filter($html->Find("tr"), "th");
if (!$result2["success"])
{
echo "Error parsing/finding table rows. " . $result2["error"] . "\n";
exit();
}
foreach ($result2["ids"] as $id)
{
echo "\t" . $html->GetOuterHTML($id) . "\n\n";
}
?>
This is what I tried with CURL and the help of a stackoverflow post (https://kleesit.de/beta/livetime/test2.php):
<?php
// random 7 chars digit/alphabet for "t" param
$random = substr(md5(mt_rand()), 0, 7);
$socket_server='https://aircrasher.livefpv.com/live/scoring/';
// create curl resource
$ch = curl_init();
//N°1 GET request
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server,
CURLOPT_RETURNTRANSFER => TRUE,
// since it is TRUE by default we should disable it
// on our localhost, but from real https server it will work with TRUE
CURLOPT_SSL_VERIFYPEER => FALSE
]);
// $output contains the output string
$output = curl_exec($ch);
$output=substr($output, 1);
echo $socket_server;
// server response in my case was looking like that:
// '{"sid":"4liJK2jWEwmTykwjAAAR","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000,"maxPayload":1000000}'
var_dump($output);
$decod=json_decode($output);
// setting ping Interval accordingly with server response
$pingInterval = $decod->pingInterval;
//N°2 POST request
$socket_server_with_sid = $socket_server.'&sid='.$decod->sid;
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server_with_sid,
CURLOPT_POST => TRUE,
CURLOPT_TIMEOUT_MS => $pingInterval,
// 4 => Engine.IO "message" packet type
// 0 => Socket.IO "CONNECT" packet type
CURLOPT_POSTFIELDS => '40'
]);
$output = curl_exec($ch);
// ok
var_dump($output);
// Pervious 2 requests are called "hand shake" now we can send a message
// N°3 socket.emit
if ($output==='ok') {
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server_with_sid,
CURLOPT_TIMEOUT_MS => $pingInterval,
CURLOPT_POST => TRUE,
// 4 => Engine.IO "message" packet type
// 2 => Engine.IO "EVENT" packet type
CURLOPT_POSTFIELDS => '42["chat message","0devhost message 10"]'
]);
$output = curl_exec($ch);
// ok
echo $output.'<br/>';
echo $socket_server_with_sid;
}
// close curl resource to free up system resources
curl_close($ch);
?>

Getting a single value from an array

I am getting a response as an array in the following format:
Array
(
[refresh_token_expires_in": "0] =>
[api_product_list": "[ops-prod]] =>
[api_product_list_json": [
"ops-prod"
]] =>
[organization_name": "epo] =>
[developer.email": "sudham#gmail.com] =>
[token_type": "BearerToken] =>
[issued_at": "1568870621501] =>
[client_id": "F4GzALmoCfWXh] =>
[access_token": "MYjtqSlOI] =>
[application_name": "8ec0-872fa20cdc59] =>
[scope": "core] =>
[expires_in": "1199] =>
[refresh_count": "0] =>
[status": "approved] =>
[error] =>
)
when i run print_r($token); i am getting the proper response.
Now i need to grab the value of only "access_token". I am not sure how to do that. I tried with $token['access_token']; but its returning null value. Can anyone help me on the same.
The following is the json response:
{"refresh_token_expires_in\": \"0":"","api_product_list\": \"[ops-prod]":"","api_product_list_json\": [\n \"ops-prod\"\n ]":"","organization_name\": \"epo":"","developer.email\": \"sudham#gmail.com":"","token_type\": \"BearerToken":"","issued_at\": \"1568871637352":"","client_id\": \"fxhYBIrh7BZHtcQeUIGF4GzALmoCfWXh":"","access_token\": \"HgARGtASwbcG":"","application_name\": \"2df9fbac-8ec0-872fa20cdc59":"","scope\": \"core":"","expires_in\": \"1199":"","refresh_count\": \"0":"","status\": \"approved":"","error":""}
Response
a:14:{s:29:"refresh_token_expires_in": "0";s:0:"";s:30:"api_product_list": "[ops-prod]";s:0:"";s:44:"api_product_list_json": [
"ops-prod"
]";s:0:"";s:24:"organization_name": "epo";s:0:"";s:39:"developer.email": "sudham#gmail.com";s:0:"";s:25:"token_type": "BearerToken";s:0:"";s:26:"issued_at": "1568871637352";s:0:"";s:45:"client_id": "4GzALmoCfWXh";s:0:"";s:44:"access_token": "ARGtASwbcG";s:0:"";s:56:"application_name": "46e2-8ec0-872fa20cdc59";s:0:"";s:13:"scope": "core";s:0:"";s:18:"expires_in": "1199";s:0:"";s:18:"refresh_count": "0";s:0:"";s:18:"status": "approved";s:0:"";}
oauth1.php
<?php
function read_token ($tokenname) {
// read token file and return token variables array
// if token not present or outdated create a new token and return new token variables array
$tokenfile="$tokenname.dat";
$error='';
if (file_exists($tokenfile)) {
$token=unserialize(file_get_contents($tokenfile));
// convert token issued time from windows (milliseconds) format to unix (seconds) format
$tokentime=substr($token['issued_at'],0,-3);
$tokenduration=$tokentime + $token['expires_in'] - 120;
if ($tokenduration < time()) {
$error.="token '$tokenname' expired.<br>\n";
} else {
$token['error']=$error;
}
} else {
$error.="tokenfile '$tokenname' not found.<br>\n";
}
if ($error) {$token=create_token($tokenname);}
return($token);
}
function create_token ($tokenname) {
// set variables
$tokenfile="$tokenname.dat";
$error='';
switch ($tokenname) {
case 'OPSincidental':
$ops_key='*******';
$ops_secret='*******';
break;
default:
$ops_key='*******';
$ops_secret='*******';
break;
}
$tokenUrl='https://ops.epo.org/3.2/auth/accesstoken';
$tokenHeaders=array(
'Authorization: Basic '.base64_encode($ops_key.':'.$ops_secret),
'Content-Type: application/x-www-form-urlencoded'
);
$tokenPostFields='grant_type=client_credentials';
$curlOpts=array(
CURLOPT_URL => $tokenUrl,
CURLOPT_HTTPHEADER => $tokenHeaders,
CURLOPT_POSTFIELDS => $tokenPostFields,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1
);
// obtain token
$token_request= curl_init();
curl_setopt_array($token_request, $curlOpts);
if (!$ops_token_response=curl_exec($token_request)) {$error.=curl_error($token_request)."<br>\n";}
curl_close($token_request);
// process token
$ops_token_split=explode(',', trim($ops_token_response,'{}'));
foreach ($ops_token_split as $tokenval) {
$tokenpair=explode(' : ', trim($tokenval));
$token[trim($tokenpair[0],'"')]=trim($tokenpair[1],'"');
}
// write token data to file
file_put_contents($tokenfile, serialize($token));
// add error information to token array and return result
$token['error']=$error;
return($token);
}
?>
oauthmain.php
<?php
// obtain token
include_once('oauth1.php');
$token=read_token('OPSincidental');
//print json_encode($token);
if (!$token['error']) {
echo "Token:<br>\n<PRE>"; print_r($token); echo "</PRE>";
// prepare for sending data request
$error='';
$requestUrl='http://ops.epo.org/3.2/rest-services/published-data/publication/epodoc/EP1000000/biblio';
//$requestUrl='https://ops.epo.org/3.2/rest-services/published-data/publication/epodoc/EP100000';
$requestHeaders=array(
'Authorization: Bearer '.$token['access_token'],
'Host: ops.epo.org',
'X-Target-URI: http://ops.epo.org',
'Accept: application/xml',
'Connection: Keep-Alive'
);
$curlOpts=array(
CURLOPT_URL => $requestUrl,
CURLOPT_HTTPHEADER => $requestHeaders,
// CURLOPT_SSL_VERIFYPEER => FALSE,
// CURLOPT_SSL_VERIFYHOST => FALSE,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 1
);
// send request and collect data
$ops_request= curl_init();
curl_setopt_array($ops_request, $curlOpts);
if (!$ops_response=curl_exec($ops_request)) { $error.=curl_error($ops_request)."<br>\n";}
echo "curl options:<br>\n";
echo "<PRE>";print_r($requestHeaders);echo "</PRE>";
curl_close($ops_request);
if ($error) {echo "Error:<br>\n$error";} else {echo "Result:<br>\n".htmlspecialchars($ops_response);}
} else {
echo $token['error'];
}
?>
Use the unserialize() function to parse that response.
$ops_token_response = file_get_contents("filename.dat");
$token = unserialize($ops_token_response);
echo $token['access_token'];
TBH I would recommend changing the way you store the token file - I would store the return value from the API directly to the file (you would be storing the JSON string). At the moment you are trying to do your own json_decode() on the response - which is not correctly extracting the data anyway...
// Do not use this bit
// process token
// $ops_token_split=explode(',', trim($ops_token_response,'{}'));
// foreach ($ops_token_split as $tokenval) {
// $tokenpair=explode(' : ', trim($tokenval));
// $token[trim($tokenpair[0],'"')]=trim($tokenpair[1],'"');
// }
// Decode the values to $token
$token = json_decode($ops_token_split, true);
// Write JSON to token file
// write token data to file
file_put_contents($tokenfile, $ops_token_response);
Then to read the file, just json_decode() the contents of the file...
if (file_exists($tokenfile)) {
$token=json_decode(file_get_contents($tokenfile), true);

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

Print values in REST API

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);

Categories