I am trying to build an array of xml files.
Each get request gives me 100 products and I need to get around 800 products.
So I tried building a loop based on a variable ts_d which u can use to get the next page of the xml.
public function getXml($division, $topic, $tsp)
{
$array = array();
$i = 0;
$x = 1;
while ($x = 1) {
$headers = ['Authorization' => 'Bearer '.$this->getAccessToken()];
$client = new Client([
'base_uri' => 'https://start.exactonline.nl/docs/',
]);
try {
$response = $client->request('GET', 'XMLDownload.aspx', [
'query' => ['Topic' => $topic, '_Division_' => $division, 'TSPaging' => $tsp],
'headers' => $headers,
]);
$string = new \SimpleXMLElement((string) $response->getBody());
$tspaging = $string->Topics->Topic->attributes()->{'ts_d'};
$array[$i]=$string;
echo $tspaging . ' ' . $tsp;
}
catch (\Exception $e) {}
if (!isset($tspaging)) {
$x = 0;
}
$i++;
$tsp = $tspaging
unset($string);
}
return $array;
}
I call this function with:
$stockPositions = $connection->getXml(1310477, 'StockPositions', '');
But this while loop is infinite and the echo returns:
0x000000000F5753AB 0x000000000F5753AB 0x000000000F5753AB0x000000000F5753AB 0x000000000F5753AB0x000000000F5753AB 0x000000000F5753AB0x000000000F5753AB 0x000000000F5753AB0x000000000F5753AB
Can you guys help met get out of this infinite loop?
The problem was that $tspaging was returning a simpleXmlObject string instead of a normal string. The solution was adding strval to that element:
$tspaging = strval($string->Topics->Topic->attributes()->{'ts_d'});
Related
dump($data) outside the foreach loop gives me only 1 data where as dump($data) inside the foreach shows all arrays of rows of data . How can i get all rows of data outside the foreach too?
$skillId = $request->skillId;
if (CourseFiles::where('skillId', $skillId)->exists()) {
$courseId = CourseFiles::where('skillId', $skillId)->get(['courseId']);
foreach ($courseId as $row) {
$id = Course::find($row);
$data = [];
$data['courseDisplayName'] = $id[0]['courseDisplayName'];
$data['courseInfo'] = $id[0]['courseUniqueName'];
$data['paidStatus'] = $id[0]['paid_status'];
$data['coursePatternsId'] = $id[0]['course_patterns_id'];
$fileId = CourseFiles::where('skillId', $skillId)->get(['fileId']);
$id = Uploads::find($fileId);
$data['filePath'] = $id[0]['FilePath'];
$contentTypeID = $id[0]['FileType'];
$id = ContentTypes::find($contentTypeID);
$data['file_height'] = $id[0]['height'];
$data['file_width'] = $id[0]['width'];
dump($data);
}
//dump($data);
if ($data) {
return response()->json([
'message' => 'Fetched Data successfully',
'data' => $data,
'statusCode' => 200,
'status' => 'success'
], 200);
}
}
EDIT:
$response[]=$data;
$response->paginate(5);
Error: Call to a member function paginate() on array
In Controller add new function for it
$data = $this->paginate($myArray);
After that crate that function for pagination
public function paginate($items, $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
return that $data in response
just do like this,
$output = array();
foreach ($courseId as $key => $row) {
$id = Course::find($row);
$fileId = CourseFiles::where('skillId', $skillId)->get(['fileId']);
$idtwo = Uploads::find($fileId);
$idthree = ContentTypes::find($idtwo[0]['FileType']);
//your data want to push to array
$output[$key] = array(
'courseDisplayName' => $id[0]['courseDisplayName'];
'courseInfo' => $id[0]['courseUniqueName'];
'paidStatus' => $id[0]['paid_status'];
'coursePatternsId' => $id[0]['course_patterns_id'];
'filePath' => $idtwo[0]['FilePath'];
'file_height' => $idthree[0]['height'];
'file_width' => $idthree[0]['width'];
);
}
dd($output);
As you can see in the JSON file, this looks not so necessary.
I get values from input-s and add it to the array and send it via AJAX. A simple array I know how to convert, but a multidimensional one is not. Can eat what that function? I tried to create an array with "keys", but there is a lot of trouble, I never reached the end , and I'm sure it's not right. Tell me what you can do.
i want this
{
"user1" : {
first_name":"Michael",
"last_name":"Podlevskykh",
"phones" : {
"phone_1":"5345",
"phone_2":"345345",
"phone_3":"123"
}
}
}
//this is what i see
JSON
[
{"first_name":"Michael"},
{"last_name":"Podlevskykh"},
[{"phone_1":"5345"},
{"phone_2":"345345"},
{"phone_3":"0991215078"}
]
]
PHP
//[["5345", "345345", "123"], "Michael", "Podlevskykh"]
$userInfo = (json_decode($_POST["phones"], true));
$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;
$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);
foreach ($jsonPhones[0] as $key => $value) {
$phones[] = array($namePhones[$key] => $jsonPhones[0][$key]);
}
foreach ($nameLName as $key => $value) {
$usersName[] = array($nameUser[$key] => $nameLName[$key]);
}
array_push($usersName, $phones);
echo "<pre>";
echo json_encode($usersName);
//[
// {"first_name":"Michael"},{"last_name":"Podlevskykh"},
// [{"phone_1":"5345"},{"phone_2":"345345"},{"phone_3":"123"}]
//]
I don't get all the complications, I would do something like this if I'm sure the $input format is the same:
<?php
$input = '[["5345", "345345", "123"], "Michael", "Podlevskykh"]';
$input = json_decode($input, true);
$output = [
'user1' => [
'first_name' => $input[1],
'last_name' => $input[2],
'phones' => [
'phone_1' => $input[0][0],
'phone_2' => $input[0][1],
'phone_3' => $input[0][2]
]
]
];
echo '<pre>';
echo json_encode($output);
If you want an object as output, you need to create an object:
$userInfo = (json_decode($_POST["phones"], true));
$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;
$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);
$user = new stdClass();
foreach ($nameLName as $key => $value) {
$user->{$nameUser[$key]} = $nameLName[$key];
}
$phones = new stdClass();
foreach ($jsonPhones[0] as $key => $value) {
$phones->{$namePhones[$key]} = $jsonPhones[0][$key];
}
$user->phones = $phones;
$users = new stdClass();
$users->user1 = $user;
echo json_encode($users);
Output:
{"user1": {
"first_name":"Michael",
"last_name":"Podlevskykh",
"phones":{
"phone_1":"5345",
"phone_2":"345345",
"phone_3":"123"
}
}
}
I am working on facebook pagination, I have searched but didn't get relevant answer.
First I am fetching 10 result and after that onclick function I want to fetch next 10 results for this I am passing -
[paging] =>
Array
(
[previous] => https://graph.facebook.com/v2.9/....D&__previous=1
[next] => https://graph.facebook.com/........
)
as parameter,I also tried passing next URL as parameter but still it is not working, if I pass $feedEdge as associated I am getting response as null,below is my code
$response = self::$_FBINSTANCE->get('/me/feed?fields=id,message&limit=' . $_pagination->limit);
if(empty($_nextFeed)){
$feedEdge = $response->getGraphEdge();
$nextFeed = $response->getGraphEdge()->getMetaData();
}else{
$feedEdge=$response->next($_nextFeed);
$nextFeed = $response->getGraphEdge()->getMetaData();
}
$result = array();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
return array(
'result' => $result,
'totalRows' => $totalCount,
'nextFeed' => $nextFeed
);
using v2.9 version, what parameter I should pass for $response->next(); help me if I am wrong .
I found solution for this question...
If any one is trying for same try below code.
$result = array();
if(empty($_nextFeed)){
$response = $fb->get('/me/feed?fields=id,message&limit=' . $_pagination->limit);
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
$nextFeed = $response->getGraphEdge()->getMetaData();
}else{
//to get until time stamp form next url
$nextURl=parse_url($_nextFeed['paging']['next']);
parse_str($nextURl['query'], $URL);
$response = $fb->get('/me/feed?fields=id,message&limit='.(($_pagination->limit)+1).'&until='.$URL['until']);
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
//because result repeats last array of previous request
array_splice($result,0,1);
$nextFeed = $response->getGraphEdge()->getMetaData();
}
return array(
'result' => $result,
'totalRows' => $totalCount,
'nextFeed' => $nextFeed
);
It works :)
I have a really weird problem, I am doing a script that executes a symfony command.
Here it is :
<?php
$checkname = 'symfony_checker';
$sensu_ip = '192.168.13.000';
$port = 3002;
function write_to_sensu($json)
{
echo('writing');
try
{
$fp = fsockopen($sensu_ip, $port, $errno, $errstr, 10);
if ($fp)
{
fwrite($fp, $json);
fclose($fp);
}
}
catch (Exception $E)
{
}
}
ini_set('max_execution_time', 0);
require_once dirname(__DIR__).'/app/bootstrap.php.cache';
require_once dirname(__DIR__).'/app/AppKernel.php';
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
$input = new ArrayInput(array(
'command' => 'security:check',
'--format' => 'json',
));
$output = new BufferedOutput();
$kernel = new AppKernel('dev', true);
$application = new Application($kernel);
$application->setAutoExit(false);
$application->run($input, $output);
$payload = array(
'name' => $checkname,
"status" => 0
);
$payload = json_encode($payload);
$arr = json_decode($output->fetch());
$vulnerabilites = array();
foreach ($arr as $key => $errors)
{
$var = 0;
foreach ($errors as $error)
{
if ($var == 1)
{
foreach ($error as $key => $one)
array_push($vulnerabilites, $key);
}
$var++;
}
}
$vulnerabilites = implode(' ', $vulnerabilites);
$payload['output'] = 'Vulnerabilities found : ' . $vulnerabilites;
dump($vulnerabilites);
write_to_sensu($payload);
Problem is that the program leave at the line :
$payload['output'] = 'Vulnerabilities found : ' . $vulnerabilites;
If I comment this line the code continue fine and goes to my function write to sensu.
If I just update $payload['output'] with a random string it doesn't work either.
Every time I try to update payload, the program quit! Anywhere in the code.
Have any idea why ?
You are converting $payload into a string with the line
$payload = json_encode($payload);
so you cannot use it as an array anymore. Either assign the result of json_encode() to another variable, or update your array before the conversion.
You've already encoded your array to JSON before you attempt to add the vulnerabilities. So you're treating a string as an associative array.
You just need to move your line
$payload = json_encode($payload);
to after this line:
$payload['output'] = 'Vulnerabilities found : ' . $vulnerabilites;
I can echo the response i get just fine in the function request_callback so I thought it trivial to just save the response into an array associative_array[], however this yields just single entries, like the array gets wiped after every entry.
I make use of https://github.com/LionsAd/rolling-curl/blob/master/RollingCurl.php
<?php
# Get the all the items numbers
$url1 = "http://api.guildwars2.com/v2/commerce/listings";
$response1 = file_get_contents($url1);
$data1 = json_decode($response1, true);
#retrieve item names and link with numbers
function request_callback($response) {
$temporary_array = json_decode($response, true);
$associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']);
// array[] places the new entry at end of urls stack, faster then array_push($array, new entry);
print_r ($associative_array);
echo "\n";
}
# Multiple curl request
require("rollingcurl.php");
for ($x=0;$x<5;$x++){
$itemurl1 = "http://api.guildwars2.com/v2/items/{$data1[$x]}";
$urls[$x]= $itemurl1;
}
$rc = new RollingCurl("request_callback");
$rc->window_size = 20;
foreach ($urls as $url) {
$request = new RollingCurlRequest ( $url ) ;
$rc -> add ( $request ) ;
}
$rc->execute();
?>
Your array is local to your function, hence reseting on each call.
Try adding global declaration and you will get what you expect (all values);
function request_callback($response) {
global $associative_array;
$temporary_array = json_decode($response, true);
$associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']);
// array[] places the new entry at end of urls stack, faster then array_push($array, new entry);
print_r ($associative_array);
echo "\n";
}
I'd create your array outside of your function. It looks like you're creating a new array on every function call.
$associative_array = array();
function request_callback($response) {
global $associative_array;
$temporary_array = json_decode($response, true);
$associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']);
// array[] places the new entry at end of urls stack, faster then array_push($array, new entry);
print_r ($associative_array);
echo "\n";
}