How to use a php variable outside the loop
how to save output result outside the loop
this variable $jsonrs
this is the result I want it outside the loop
"1""1.jpg""2""2.jpg""3""3.jpg""4""4.jpg"
$url = 'https://hentaifox.com/gallery/58769/';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
preg_match_all('!<img class="lazy no_image" data-src="(.*?)"!', $result, $manga_name);
$items = array();
foreach ($manga_name[1] as $key => $manganm) {
$imag_manga = str_replace('t.jpg','.jpg',$manganm);
$imagerep = 'https:'.$imag_manga;
$filename = basename($imagerep);
$imag_num = str_replace('.jpg','',$filename);
$array_name = array($imag_num => $filename);
$json1 = json_encode($imag_num);
$json2 = json_encode($filename);
$jsonrs = $json1.$json2;
print_r($jsonrs);
}
Your end result in $jsonrs is a bit unusual, I (am assuming) that you want to JSON encode the list of images, if so then use $items to keep a list of each image and then json_encode() this list after the loop...
foreach ($manga_name[1] as $key => $manganm) {
$filename = basename($manganm);
$imag_num = str_replace('t.jpg','',$filename);
$items[$imag_num] = $filename;
}
echo json_encode($items);
will give you
{"1":"1t.jpg","2":"2t.jpg","3":"3t.jpg","4":"4t.jpg"}
Related
So, I have one curl API call which works fine when I do foreach outside the while loop. Once I move the foreach inside (because I need the values inside) it becomes an infinity loop.
This is the setup
$query = "SELECT id, vote FROM `administrators` WHERE type = 'approved'";
$result = $DB->query($query);
$offset = 0;
$length = 5000;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
do {
curl_setopt($ch, CURLOPT_URL, "https://api.gov/data?api_key=xxxxxxxxxx&start=1960&sort[0][direction]=desc&offset=$offset&length=$length");
$jsonData = curl_exec($ch);
$response = json_decode($jsonData);
foreach($response->response->data as $finalData){
$allData[] = $finalData;
}
$offset += count($response->response->data);
} while ( count($response->response->data) > 0 );
curl_close($ch);
while($row = $DB->fetch_object($result)) {
foreach ( $allData as $key => $finalData1 ) {
// rest of the code
}
}
Once I run the page it goes infinity or until my browser crash. If I move foreach ( $allData as $key => $finalData1 ) { } outside the while(){} there is no such problem.
Any ideas on what can be the problem here?
UPDATE: // rest of the code
$dataValue = str_replace(array("--","(s)","NA"),"NULL",$finalData1->value);
if($frequency == "dayly") {
if($dataValue) {
$query = "UPDATE table SET $data_field = $dataValue WHERE year = $finalData1->period AND id = $row->id LIMIT 1";
}
}
if(isset($query))
$DB->query($query);
unset($query);
One of the issues could be that where
// rest of the code
is, you have duplicate variable names, thus overriding current positions in arrays and loops.
However, you should change your approach to something like
$rows = Array();
while($row = $DB->fetch_object($result)) $rows[] = $row;
foreach ($rows as $row) {
foreach ($allData as $key => $finalData1) {
// rest of the code
}
}
That way you can read resultset from database faster and free it before you continue.
im trying to grab the contents from a URL(which is a json) that changes for each iteration of my loop. The problem with my method of doing things is that it is very slow and if I do about 120 iterations it takes over 40sec.
Here is my code:
$GetFriendListUrl = "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=mykey&steamid=".$other_steamid."&relationship=friend";
$GET_GetFriendListUrl= file_get_contents($GetFriendListUrl);
$raw_ids = json_decode($GET_GetFriendListUrl , TRUE);
$count = count($raw_ids['friendslist']['friends']);
$ci = curl_init();
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
for ($x = 0; $x <= $count; $x++) {
$friendslist = $raw_ids['friendslist']['friends'][$x]['steamid'];
curl_setopt($ci, CURLOPT_URL, "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=mykey&steamids=".$friendslist);
$cont = curl_exec($ci);
$contFull = json_decode($cont, true);
$steamname = $contFull['response']['players'][0]['personaname'];
$steamprofileurl = $contFull['response']['players'][0]['profileurl'];
$friendimage = $contFull['response']['players'][0]['avatar'];
$friendimageData = base64_encode(file_get_contents($friendimage));
echo '<img class="other_friendsteamimage" src="data:image/jpeg;base64,'.$friendimageData.'">';
echo "<a class='other_friendlabel' href='$steamprofileurl'>$steamname</a>";
echo "<br>";
}
curl_close($ci);
I cannot be sure of the format of the data returned by the api and I have no means of testing the following but in line with the comment I made and based upon the documentation it would appear that sending few requests but with each request dealing with 100 steamIDs you should save considerable amount of time.
/* get the intial data */
$url = "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=mykey&steamid=".$other_steamid."&relationship=friend";
$data= file_get_contents( $url );
$json = json_decode( $data );
$ids=array();
/* just grab the IDs and add to array - correct format to access records??? */
foreach( $json->friendslist->friends as $obj ){
$ids[]=$obj->steamid;
}
/* split the IDs into chunks of 100 */
$chunks=array_chunk( $ids, 100 );
/* send a request per chunk of 100 */
foreach( $chunks as $chunk ){
$url=sprintf('https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=mykey&steamids=%s',implode(',',$chunk));
$curl = curl_init( $url );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$res=curl_exec( $curl );
if( $res ){
$data=json_decode($res,true);
/* do stuff .... */
}
curl_close($curl);
}
echo 'Finito';
I've been trying to run CURL in a foreach loop to extract information from the cryptocompare.com API. As soon as I call the following function, my code just stops working. There is no output.
$fullArray[$symbol]['Price'] = getThePrice($fullArray[$symbol]['Symbol']);
What am I doing wrong? I pasted the code below
include 'helper.php';
$fullArray = array();
//Get List of All Coins and store symbol and ID
$url = "https://min-api.cryptocompare.com/data/all/coinlist";
$jsonArray = getConnection($url);
foreach($jsonArray['Data'] as $value)
{
$symbol = $value['Symbol'];
$fullArray[$symbol]['Symbol'] = $value['Symbol'];
$fullArray[$symbol]['Id'] = $value['Id'];
//call getThePrice function to get Price of ticker
$fullArray[$symbol]['Price'] = getThePrice($fullArray[$symbol]['Symbol']);
}
function getThePrice($input)
{
//Get current price of each coin and store in full array
$url = "https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=".$input."&tsym=USD";
$jsonNewArray = getConnection($url);
if(array_key_exists('PRICE',$jsonNewArray['Data']['AggregatedData']))
{
$returnVariable = $jsonNewArray['Data']['AggregatedData']['PRICE'];
echo "The price of : ".$input." is ".$returnVariable;
}
else{
$returnVariable = "NA";
echo "This price is not available";
}
return $returnVariable;
}
The code in helper.php:
function getConnection($inputHelp)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$inputHelp);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
echo curl_error($ch);
}
curl_close($ch);
$jsonArray = json_decode($json, true);
return $jsonArray;
}
Appreciate any help. Thanks in advance.
I got 5550 records of different routes and I need to do a foreach loop for each record and get the API data.
So I made a function with Guzzle in Laravel:
public function getDirectionDistance($origins, $distinations)
{
$client = new Client();
$res = $client->get("https://maps.googleapis.com/maps/api/distancematrix/json?origins=$origins&destinations=$distinations&key=ччч")->getBody()->getContents();
$obj = json_decode($res, true);
$distance = $obj['rows'][0]['elements'][0]['distance']['text'];
$clean = $string = str_replace(' km', '', $distance);
return $clean;
}
I used it in a store method
public function store()
{
$route = $this->route->with('from','to')->get();
$maps = new Maps();
foreach ($route as $item){
$direction = new Direction();
$from = $item->from->name;
$to = $item->to->name;
$direction->route_id = $item->id;
$direction->distance = $maps->getMapsApi("$from,israel","$to,israel");
$direction->save();
sleep(3);
}
}
But when I do It, I get 1 distance for 200 routes and then after 200 row I get the next distance for the next route. How to stop and wait for api to be completed, save it and then start the next row. I need the data to create a Machine Learning price calculator.
For me work in this way:
I created a function that make a call to google with CURL:
public function calculateDistance($origins, $destination){
$staticDistanceModel = New StaticDistance();
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" . $origins . "&destinations=" . $destination . "&mode=driving&language=it-IT&key=xyz";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
if (isset($response_a['rows'][0]['elements'][0]['distance']['value'])) {
$m = $response_a['rows'][0]['elements'][0]['distance']['value'];
}else{
$m = 0;
}
$staticDistanceModel->insertStatic($origins, $destination, $m);
}
}
the function in my model is something like:
public function insertStatic($origins, $destination, $m){
$arrayInsert = array('origins'=>$origins, 'destination'=>$destination,'distance'=>$m);
Self::create($arrayInsert);
}
And in my controller I have forEach() like this:
foreach ($array as $object) {
$calculator = $this->calculateDistance($object->origins, $object->destination);
}
But be careful because google limit request, and the time for 5500 records maybe long, so you can chunk array.
Hope this can help you
i just want get the data from the json link with the id == 0
how i can make this !?
<?php
$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
$wins = $value['totalTripleKills'];
}
}
?>
my code doesn't show anything ..
can anyone help !?
Your not outputing anything, your just assigning $wins over and over, there could also be an issue with file_get_contents not working as expected with over https urls.
Its faster and easyier to use cURL, also after a quick test it seems,
$value['totalTripleKills'] should be $value['stats']['totalTripleKills']
<?php
$url = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
curl_close($curl);
if(empty($result)) {
echo 'Error fetching: '.htmlentities($url).' '.curl_error($curl);
}else{
$gaza = json_decode($result, true);
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
echo $value['stats']['totalTripleKills'].'<br>';
}
}
}
Also its a rather large response so you will want to look into caching the result for a while, but thats beyond the questions scope.
There is an error you forgot to enter first in the stats array, otherwise you cannot take totalTripleKills value, then output it.
$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
$wins = $value['stats']['totalTripleKills'];
}
}
echo $wins;
Before you parse a json a helpful method to understand json structure of your data is this website: http://jsonlint.com/.
your not outputting anything,
<?php
$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
$wins = $value['totalTripleKills'];
}
}
?>
try this
<?php
$claw = "https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/43216818/ranked?season=SEASON4&api_key=010ba2bc-2c40-4b98-873e-b1d148c9e379";
$z0r = file_get_contents($claw);
$gaza = json_decode($z0r, true);
echo "<pre>";
foreach ($gaza['champions'] as $key => $value) {
if ($value['id'] == 0) {
$wins = $value['totalTripleKills'];
var_export( $wins );
}
}
?>