How do I cache data from a JSON API in PHP? [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In my PHP app I am retrieving data from a REST API (namely PokeAPI) and want to be able to cache the information I retrieve from it in order to cut down on time and API requests. What would be the best way to go about doing this?
Here is the code I am using the API for:
<?php
$base = "http://pokeapi.co/api/v2/pokemon/";
if (isset($_POST["dexno"])) {
$dexarray = $_POST["dexno"];
foreach( $dexarray as $d ) {
$data = #file_get_contents($base.$d);
if ($data != "") {
$pokemon = json_decode($data);
$img = $pokemon->sprites->front_default;
$imageData = base64_encode(file_get_contents($img));
echo '<img src="data:image/png;base64,'.$imageData.'">'.'<br>';
echo $pokemon->name.'<br>';
} }
}
?>
This simply takes numerical data from an array, puts it into a URL and pulls information from the URL generated. Any help would be much appreciated, as I have only just started learning PHP.

Like this:
$json = ""; //your json string.
$fh = fopen("myCacheFile.jsoN" , "w+");
fwrite($fh , $json);
fclose($fh);
If you want short code:
file_put_contents("myCacheFile.json" , $json);
To Retrieve:
$arr = json_decode(file_get_contents("myCacheFile.json") , true);

You can simply store the data in file on disk, and next time before making the call read from disk.
You can store it in database, and read from there.
You can use redis / memcached to store it in memory.

Related

Formatting multilevel JSON data in PHP from remote file [SOLVED] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
I am trying to extract json data from a remote php file (not a json file) so that it each time the page is propagated it pulls the newest data to format. Here are examples of what I am trying to accomplish but I cant get it to work.
resc_payouts.php
{"number":1,"username":"ivalenel"},{"number":2,"username":"newb-6763"},{"number":3,"username":"jeremyhipps"},{"number":4,"username":"dcollier200"},{"number":5,"username":"AdrianEric311"},{"number":6,"username":"Prxnce24"},{"number":7,"username":"Bungy2004"},{"number":8,"username":"sevyf7"},{"number":9,"username":"jerocker79"},{"number":10,"username":"Djmoonknight8"},{"number":11,"username":"marcel_g_l"},{"number":12,"username":"zebuss"},{"number":13,"username":"fourZer0"},{"number":14,"username":"himalayabpatel"},{"number":15,"username":"Chip1234"},{"number":16,"username":"AsvpJ9k"},{"number":17,"username":"himmy23"},{"number":18,"username":"Chip1234"},{"number":19,"username":"Clares20"},{"number":20,"username":"ballermoss"},{"number":21,"username":"gareagan04"},{"number":22,"username":"cweatherfordinc"}
jsontest.php
<?php
$content = file_get_contents('https://**********.com/manage/resc_payouts.php');
$decoded_json = json_decode($content, true);
foreach($decoded_json as $key => $value) {
$username = $decoded_json[$key]["username"];
echo $username;
}
?>
I have tried many methods, converting to a string, encoding and then decoding but cant seem to figure this out. Any help on getting this remote data off a php file and formatting it would be immensely useful.
So after a few hours i found a solution
SOLUTION FOUND
<?php
$content = file_get_contents('https://**********.com/manage/resc_payouts.php');
$json = json_decode($content, TRUE); // decode the JSON into an associative array
foreach ($json as $key => $value) {
echo $value['number'];
echo $value['username'];
echo "<br/>";
}
?>
Thanks but i figured this out myself over time

I cannot decode or extract any information from this string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How to decode the following string so I can extract readable data from it:
"H4sIAAAAAAAAAEWRz3LaMBDG…HXHYhZxEsNvDIH3B4ACAAA="
The only thing that I know about this string is that it may be random generated bytes, that's all I know, unfortunately.
I tried base64_decode() but that didn't work it just gave me this string:
?E??r?0?q??D??? }???
echo base64_decode("H4sIAAAAAAAAAEWRz3LaMBDG…HXHYhZxEsNvDIH3B4ACAAA=");
This string should give me really useful information for the API project I'm working on, also if there is an alternative way to do this using javascript please let me know, Thanks.
I have searched for H4sIAAA and found gzdecode() which decoded this string, thank you for your help Pavan Kumar.
$string = "H4sIAAAAAAAAABWPQU+DQBCFH7RVICaeTDyZ7cGrB5PGM4XVNhLiofXaTGGkG2Fp2MXIL+J/8MOM27m9b95M3ouAEJ6KAHg+fFV6bx4WSdtr60WYWapCzFkXJ1xmhnCjSn6tqTJO/kW4LpU51zQ4V9Z2HDi6wMM0vmx10TEZNsKeWJgzcynaLzG0fYel2zdKq1aL4yCmkZ5Xjw49ib2uVaMsl7hxOu07ss60dE+jaVxNYy0/tkmAeU4N494h6ZKRdgciox8S6774ZosIt/LXdhRb26ljb9kEl2q4k3myifOdTA9Z/Bkf1vvkXe4AH1cpNVTxpeM/Fr19kRIBAAA=";
echo gzdecode(base64_decode($string))
//Result i idGCount tag ench HideFlags� display Lore §7Increases the speed of your!§7minion by §a25%§7. Unlimited§7Duration! §5§lEPICName§5Enchanted Lava Bucket ExtraAttributesidENCHANTED_LAVA_BUCKETDamage
You can get quite close using the following:
function inspect( $s ){
$b=rawurldecode( base64_decode( trim( $s ) ) );
$g=gzdecode( $b );
return sprintf('<pre>%s</pre>',print_r($g,1));
}
$i=0;
$max=10;
$url='https://api.hypixel.net/skyblock/auctions?key=09828659-42c5-4360-9203-d93bcb5df79d';
$data=file_get_contents( $url );
$json=json_decode( $data );
foreach( $json->auctions as $obj ){
echo inspect( $obj->item_bytes );
if( $i >= $max )break;
$i++;
}
sample output:
i
idGCount
tag ench HideFlags�
display Lore§7Increases the speed of your!§7minion by §a25%§7. Unlimited§7Duration!
§5§lEPICName§5Enchanted Lava Bucket
ExtraAttributesidENCHANTED_LAVA_BUCKETDamage

Whats the difference between these two functions [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I created a function in PHP first and then following it tried to make the same thing in Python. Following are my codes
Python:
def bfs(my_data):
my_queue = []
my_queue.insert(0, my_data[0]);
my_data[0]['visited'] = '1';
while my_queue:
vertex = my_queue.pop()
print(vertex['letter'])
for n_vertex in vertex['neighbors']:
int_vertex = int(n_vertex)-1
if my_data[int_vertex]['visited'] is '0':
my_data[int_vertex]['visited'] = '1'
test.insert(0, my_data[int_vertex])
my_queue = str(test)
PHP:
function bfs($my_data)
{
$my_queue = array(); //array to store vertices
array_unshift($my_queue, $my_data[0]); // pass the first value to the first index of queue
$my_data[0]['visited'] = true; // value for visited is set to true for the first vertix
//print_r($my_queue);
while(!empty($my_queue))
{
$vertex = array_pop($my_queue); // passing the last value of queue to vertex
echo $vertex['letter'];
$msg = $vertex['letter'];
$output_file = $_POST["output_file_name"];
$output_file_path = "../SPA/" . $output_file;
$outfile = fopen($output_file_path, 'aw'); //writing output to the file
fwrite($outfile, $msg);
fclose($outfile);
// fwrite($outfile, $msg);
foreach($vertex['neighbours'] as $n_vertex)
{
//print_r($n_vertex);
if(!$my_data[$n_vertex-1]['visited'])
{
$my_data[$n_vertex-1]['visited'] = true; // set visited true after visiting each neighbour
array_unshift($my_queue, $my_data[$n_vertex-1]); //pass the neighbours to queue
}
}
}
}
I believe both are same functions but as i am getting different results i am trying to find out the difference. What do you think? Also, if they are different can you tell me how?
This is quite a broad question (what results are you seeing, what do you suspect?) But, for one thing, the for loop in Python is not indented to be within the while, whereas in PHP it is inside the while loop.

Writing array to a file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In the program below
$array[name1][0] = 'name';
$array[name1][1] = '11';
$array[name2][0] = 'name2';
$array[name2][1] = '11';
$fileName = "file.php"
$fp = fopen($fileName,'w');
$msg = $array;
fwrite($fp,$msg);
fclose($fp);
In this file "file.php", i want to write an array...such tha its read like
<?
$array[name1][0] = 'name';
$array[name1][1] = '11';
$array[name2][0] = 'name2';
$array[name2][1] = '11';
but it's not working.
Use json_encode or serialize to get a storable (and compact) representation of your data structure, then json_decode or unserialize to get it back.
The var_export function does just that:
fprintf($fp, '<?php $array = %s;', var_export($array, true));
It generates valid PHP code and you can include the file after that:
include "file.php";
Note that you can return from a PHP file, so this would work too:
fprintf($fp, '<?php return %s;', var_export($array, true));
And then:
$array = include "file.php";
Alternatives to generating PHP code are json_encode/json_decode, or serialize/unserialize.
You can do it like this:
fwrite($fp,print_r($msg,true));
If you want to be able to read the file later and get an PHP array back, then you need to "serialize" the array:
and later
$array = unserialize(file_get_contents("test.data"));
if it should look readable in the file, you var_export($array,1) or print_r($array,1) and store their output.
The closest you're going to get, natively, is by using var_export and writing its return value to the file.
Failing that, you should implement something to build that format from an Array.

Echoing JSON array in PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
After trying for a long period of time I am a bit stuck... I want to echo a value (url) in a json array with PHP and get it into a variable.
PHP:
$coverphotos = $facebook->api('http://graph.facebook.com/' . $album['id'] . '/picture?type=album&redirect=false&access_token=' . $access_token);
JSON:
{
"data": {
"url": "http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/480080_567808343263483_176928672_a.jpg"
}
}
I want to get the actual url into a php variable... how would I go about doing this?
HOLY THAT TOOK LONG ENOUGH BUT I FIGURED IT OUT:
$coverphotos2 = $coverphotos['id'] . '?type=album&redirect=false&access_token=' . $access_token;
$content = file_get_contents($coverphotos2);
$photoarray = json_decode($content, TRUE);
$coverurl = $photoarray['data']['url'];
From the $coverphotos variable, you can store the URL of the picture with:
$picture = $coverphoto['id'];

Categories