Why my second call on url doesn't work (Laravel,Guzzle)? - php

This is a function where i call 2 api, from first i get client_id which i used in second url. Problem is that after i call second url my page is loading without end.
Page image
public function getDevices(){
$route='http://localhost:8000/api/devices';
$device= new Client();
$answer= $device->request('GET', $route);
$body = $answer->getBody();
$status = 'true';
$message = 'Data found!';
$final= json_decode($body);
$id_array = array();
foreach ($finalas $item) {
// Add each id value in your array
$id_array[]= $item->clientId;
}
foreach($id_array as $my_id) {
$answer2= $client->request('GET', 'http://localhost:8080/api/devices/deviceAvailability/' . $my_id );
$body2 = $response2->getBody();
$final2= json_decode($body2);
}
return view('new.home', ['clients' => $final, 'status'=> $final2]);

I think
return view('new.home', ['clients' => $final, 'status'=> $final2])
is wrong. Because $final is decoded variable, maybe $final contains several types of variables.
In php, you can not set parameter that contains several types of variables.
Please do like that.
return view('new.home', ['clients' => $body, 'status'=> $final2]);
That's because json encoded variable is only a string.
I want your result.

Related

How to use optional parameters in Google Photos API?

I am working on project in php with Google Photos API. i have an issue, if i pass optional parameters like pageSize, it doesn't work still get all images.
$optParams = array(
'pageSize' => 1,
);
$response = $photosLibraryClient->listMediaItems($optParams);
foreach ($response->iterateAllElements() as $item) {
$id = $item->getId();
$description = $item->getDescription();
$mimeType = $item->getMimeType();
$productUrl = $item->getProductUrl();
$filename = $item->getFilename();
echo '<br>';
echo $filename;
}
I'm not a 100% sure of this, but it seems the iterateAllElements literally iterates over all elements available in the account, ignoring your specified pageSize (even the default pageSize) by requesting everything from the API without any boundaries.
You can iterate over the returned pages replacing iterateAllElements with iteratePages, but it also doesn't seems to work properly without a albumId, the API returns an irregular page sizing, like the example below:
$optParams = array(
'pageSize' => 5 // Changed
);
$response = $photosLibraryClient->searchMediaItems($optParams); // Changed the method
foreach ($response->iteratePages() as $key => $page) {
echo "Page #{$key}<br>";
foreach ($page as $item) {
$id = $item->getId();
$description = $item->getDescription();
$mimeType = $item->getMimeType();
$productUrl = $item->getProductUrl();
$filename = $item->getFilename();
echo '<br>';
echo $filename;
}
}
if the search or list were called without providing a albumId, the example above would return something like this:
[
[{...},{...},{...}],
[{...},{...},{...},{...},{...}],
[{...}],
[],
[{...},{...},{...},{...},{...}],
[]
]
If you find a good solution for this specific problem, please let me know.
Ps.: Their API behavior and it's documentation are very weird and confusing.

Array becoming multi-dimensional in AJAX request

So I am creating a function in WordPress which counts and sets a user session and storing its values in the user's local storage. I was able to make it work perfectly by using cookies and when the site is hosted locally, for some reason, it is not working when I uploaded it on the staging site. So I am trying implement this function using another approach and decided to use local storage instead.
There's a problem with the Array values that the function is generating and I have spent almost the entire day trying to debug the problem. It is generating multi-dimensional instead of a single one.
Here's my function code:
function monitor_post_views() {
$page_id = 'page' . $_POST['page_id'];
$timestamp = time();
// 30 minutes timeout
$timeout = 1800;
// Serves as my guide for debugging, will not include in the final code
$message = '';
if ( ! empty($_POST['page_id_array']) ) {
//Checks if values from local storage exist
//Gets the stored Array coming from AJAX call
$page_id_array[] = json_decode(stripslashes($_POST['page_id_array']), true);
if ( in_array_r($page_id_array, $page_id) ) {
//Check if current page is found in array
$message = 'FOUND IN ARRAY CHECKING !!!!';
$temp= [];
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array_temp;
//Pushes the generated array inside the $page_id_array
array_push($page_id_array, $temp);
print_r(json_encode($page_id_array));
foreach ( $page_id_array as $page ) {
//If page is in array, check if the session is expired, if not, do nothing, if expired, update and then run the view function
}
} else {
// ID Not found in Array, Insert a new entry
$message = 'ID NOT FOUND IN ARRAY, CREATING ENTRY !!!';
$temp = [];
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array_temp;
//Pushes the generated array inside the $page_id_array
array_push($page_id_array, $temp);
print_r(json_encode($page_id_array));
//Set post view function here base on $_POST['page_id']
}
} else {
//Not found in local storage, need to create one
$message = 'CREATING A NEW ENTRY !!!!';
$temp = [];
$page_id_array = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array;
print_r(json_encode($temp));
//Set post view function here base on $_POST['page_id']
}
wp_die();
}
add_action('wp_ajax_monitor_post_views', 'monitor_post_views');
add_action('wp_ajax_nopriv_monitor_post_views', 'monitor_post_views');
Here's a screenshot of what this function generates
Array
Here's a sample JSON
[[{"id":"page1202","expiration":1551125579,"message":"FOUND IN ARRAY CHECKING !!!!"},{"id":"page1206","expiration":1551125613,"message":"ID NOT FOUND IN ARRAY !!!! INSERTING ENTRY !!!"}],{"id":"page1296","expiration":1551125624,"message":"ID NOT FOUND IN ARRAY !!!! INSERTING ENTRY !!!"}]
I was trying to generate a one dimensional but ended up with this.
Any thoughts? Thanks in advance
The problem is you are creating arrays too many times:
Change $page_id_array and $page_id_array_temp to
$page_id_array=new \stdClass();//no need to declare as an array
replace
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
with
$page_id_array->id=$page_id;
$page_id_array->expiration=$timestamp;
$page_id_array->message=$message;
also change
$temp = [];
you can use it directly
//no need to declare $temp as an array
$temp=$page_id_array;

How can I select the key to remove? PHP and JSON

I'm trying to select a dynamic method to remove key from a json file,at the moment, this code overwrite ALL json file and write {"0":{"name":null,"url":null}} do you know how can I solve it? I just want delete ONE key when I press delete button.
PHP:
<?php
var_dump($_POST);
$data_url = 'js/json.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
$data[] = array(
'name' => $name,
'url' => $url
);
foreach($data as $key=>$val){
// check status
if ($val["status"]=="DELETE"){
// this deletes record from array
unset($data[$key]);
}
}
file_put_contents('js/json.json', json_encode($data, JSON_FORCE_OBJECT));
header('Location: http://URL/index.php');
?>
JSON:
[{"name":"asdf","url":"asdf"},{"name":"asfd","url":"dsaf"}]
You are reading the data into $data_array and writing out $data, so what you are writing is the data you want to delete - after you've processed it to delete all the records.
What this code does is take the $url value (from however it's set) and goes through the $data_array read from the input file and if it finds a match, it removes it. Then writes out $data_array back to the file.
$data_url = 'js/json.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
// Next line just for testing
//$url = "asdf"; // $_POST['URL']; ?
foreach($data_array as $key=>$val){
// check URL
if ($url == $val["url"]){
// this deletes record from array
unset($data_array[$key]);
}
}
$data_array = array_values($data_array);
file_put_contents($data_url, json_encode($data_array));

Sending JSON Array via PHP (Campaign Monitor)

I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php
This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}

array_key_exists() expects parameter 2 to be array, string when using pushWoosh Class

I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.

Categories