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.
Related
I am trying to pull data from API for active collab, but in the body to the task exist tags HTML, causing a mess in the coding, anybody know what I can do?
My code to push API:
try {
function listTasks() {
$ch = curl_init();
$token = 'token';
curl_setopt_array($ch, [
CURLOPT_URL => 'https://collab.cadastra.com.br/api/v1/projects/projectnumber/tasks/',
CURLOPT_HTTPHEADER => [
'X-Angie-AuthApiToken: ' . $token,
'Content-Type: application/json',
'x-li-format: json'
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS
]);
$result = curl_exec($ch);
// $tasks = json_decode($result, true);
// for ($i = 0; $i < count($tasks); $i++) {
// if ($tasks[$i]["task_list_id"] == 55979) {
// $tasks_name[$i] = $tasks[$i]["name"];
// }
// }
print_r(filter_var($result, FILTER_SANITIZE_MAGIC_QUOTES));
curl_close($ch);
// return $resultado;
}
listTasks();
} catch (Error $e) {
print_r($e->getMessage());
}
// print_r($_POST['email']));
This return:
you can use one of PHP function for clean view:
strip_tags (https://www.php.net/manual/en/function.strip-tags)
htmlentities (https://www.php.net/manual/en/function.htmlentities)
for view the tasks, otherways you must look at the source of request, cause browser is rendering html. if you will have any errors for this, you can the function use for task body.
I hope it help to you. :)
i need to transform a return JSON in Array, to manipulate the datas, but when trying this array is set as null, i need to use htmlentities why this return in navigator was messed up by the html tags in json.
this is my code:
<?php
try {
function listTasks() {
$ch = curl_init();
$token = 'token';
curl_setopt_array($ch, [
CURLOPT_URL => 'https://collab.cadastra.com.br/api/v1/projects/idproject/tasks/',
CURLOPT_HTTPHEADER => [
'X-Angie-AuthApiToken: ' . $token,
'Content-Type: application/json',
'x-li-format: json'
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS
]);
$result = curl_exec($ch);
$convert = htmlentities($result, ENT_QUOTES, "UTF-8"); // I did this because the return had html tags that gave problems with browser display.
$tasks = json_decode($convert, true); //this is where I convert to array.
// for ($i = 0; $i < count($tasks); $i++) {
// if ($tasks[$i]["task_list_id"] == 55979) {
// $tasks_name[$i] = $tasks[$i]["name"];
// }
// }
var_dump($tasks); // here it returns null, if I put print_r returns nothing.
curl_close($ch);
// return $result;
}
listTasks();
} catch (Error $e) {
print_r($e->getMessage());
}
// print_r($_POST['email']));
Someone can help me ?
If the cURL request is responding with JSON format, you should first decode it with
json_decode
and then only use
htmlentities
for specify array index'es to clear the text. Then you use your way, you make json string invalid, so it can't decode it. anyway you should not use mixed json with html to display it into browser.
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;
}
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);
I am creating a Restful WebService with CakePHP 2 however, i am getting 500 Internal Server Error since i am not able to capture Post Data. The Rest Server is as below:
App::import ( 'Vendor', 'ExchangeFunctions', array ('file'=> 'exchange/exchangefunctions.php'));
class ExchangeController extends AppController
{
public $components = array('RequestHandler');
public
function index()
{
$exchange = new ExchangeFunctions();
$data = $this->request->data('json_decode');
$exchange->username = $_POST['username'];
$exchange->password = $_POST['password'];
$emailList = $exchange->listEmails();
$response = new stdClass();
$response->emailList = $emailList;
foreach($emailList->messages as $listid => $email)
{
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$_POST['attachmentPath']
);
$response->emails[$tempEmail['attachmentCode']] = $tempEmail;
}
$this->set('response', $response);
$this->set('_serialize','response');
}
}
and the client goes as:
class ApitestController extends AppController
{
Public function index()
{
$this->layout = 'ajax';
$jRequestURLPrefix = 'http://localhost/EWSApi/';
$postUrl = $jRequestURLPrefix."exchange/index.json";
$postData = array(
'username' => 'username',
'password' => 'password',
'attachmentPath'=> $_SERVER['DOCUMENT_ROOT'] . $this->base . DIRECTORY_SEPARATOR . 'emailDownloads' . DIRECTORY_SEPARATOR . 'attachments'
);
$postData = json_encode($postData);
pr($postData);
$ch = curl_init( $postUrl );
$options = array(
CURLOPT_RETURNTRANSFER=> true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
),
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS => $postData,
);
curl_setopt_array( $ch, $options );
$jsonString = curl_exec($ch);
curl_close($ch);
$data = json_decode($jsonString, FALSE);
echo $jsonString;
}
}
Not sure where i am messing up! Please help!
Ok, after a second look there are some more suspicious things. As already mentioned, your CURL request uses GET instead of POST.
$options = array(
...
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postData,
);
Another thing is that you are encoding the POST data for your CURL call to JSON, but then you are trying to access it on the other side using $_POST, however there won't be anything, POST data would have to be key/value query string formatted in order to appear in $_POST. You have to read php://input instead, which may be what you were trying to do with
$data = $this->request->data('json_decode');
However you must use CakeRequest::input() for that purpose, and of course you must then use the $data variable instead of $_POST
$data = $this->request->input('json_decode');
$exchange->username = $data['username'];
$exchange->password = $data['password'];
....
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$data['attachmentPath']
);
Also make double sure that your CURL request looks like expected:
$options = array(
...
CURLOPT_POSTFIELDS => $postData,
CURLINFO_HEADER_OUT => true // supported as of PHP 5.1.3
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
print_r($info);
echo '</pre>';