cURL inside foreach loop not working - php

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.

Related

PHP - Combine multiple API endpoints in array

I am trying to create a small function to load data from different API endpoints into one array to work with / load data from. Right now my code is looking as follow;
$url1 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/uhmotNBAQ6-0vi9PFysRBg/members';
$url2 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/DWkD4B0uSsGQoryrz8Nuwg/members';
$url3 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/wSbCgimqTPy470n-wDQXPQ/members';
$url4 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/nmc0HQW-TZirTlnGzwbF-w/members';
$url5 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/WpV4yaVxSLW8QXH2Be40cA/members';
$api_endpoint1 = json_decode(file_get_contents($url1), true);
$api_endpoint2 = json_decode(file_get_contents($url2), true);
$api_endpoint3 = json_decode(file_get_contents($url3), true);
$api_endpoint4 = json_decode(file_get_contents($url4), true);
$api_endpoint5 = json_decode(file_get_contents($url5), true);
$merged_data = array();
foreach ($api_endpoint1 as $data) {
foreach ($api_endpoint2 as $data2) {
$merged_data[] = array_merge($data, $data2[$data['Name']]);
}
}
var_dump($merged_data);
It doesn't work as I tried so many things the past two days, I came to search for help.
Huge thanks to #barrycarter for his help in pushing me into the right direction.
The actual code needed to be like this:
$url1 = 'gameinfo.albiononline.com/api/…';
$url2 = 'gameinfo.albiononline.com/api/…';
$url3 = 'gameinfo.albiononline.com/api/…';
$url4 = 'gameinfo.albiononline.com/api/…';
$url5 = 'gameinfo.albiononline.com/api/…';
$merged_urls = [$url1, $url2, $url3, $url4, $url5];
$api_endpoint = [];
foreach ($merged_urls as $urls) {
$api_endpoint[] = file_get_contents($urls);
}
// Gives all DATA from all Guilds members
// var_dump($api_endpoint);
$merged_arrays = array_merge(json_decode($api_endpoint[0], true), json_decode($api_endpoint[1], true), json_decode($api_endpoint[2], true), json_decode($api_endpoint[3], true), json_decode($api_endpoint[4], true));
foreach ($merged_arrays as $query) {
echo $query['Name'];
echo '<br>';
}

I need to load the distance data from Google Maps and save it to my Database

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

Loop over Array in array

I've got this data: http://api.tvmaze.com/shows?page=0
What i am trying to achieve is looping over the data and echo each id. This is the code i used:
<?php
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
foreach( $response as $serie){
foreach( $serie as $info => $value){
echo $info->$value["id"];
}
}
I don't really know what i am doing wrong.. Do you guys have any idea?
Greetz,
Try below code for getting id and url. You have to use array because you are passing TRUE in json_decode().
<?php
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
foreach( $response as $serie)
{
echo $serie['id']."->".$serie['url']."<br>";
}
?>
Keep it simple to fetch ids you wanted,
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
echo "<pre>";
foreach ($response as $value) {
echo $value['id']."<br/>"; // you will get ids in here only
}

Getting Php Curl Error

I want to grab first 10 results of that any url i passed it to function as parameter ..and i want to make data scraper for some sites
Getting Syntax error when I print the result on screen
syntax error on this line I don't why it giving me syntax error kindly help me....
print_r( $dse->crawl()->parse() );
<?php
class CURL_CRAWLER{
public $url;
public $request_type;
public $data;
public $post_params;
function __construct($url = '' , $request_type = 'GET')
{
$this->url = $url;
$this->request_type = $request_type;
$this->data = '';
$this->post_params = array();
}
/**crawl a document **/
function crawl()
{
$curl = curl_init( $this->url );
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_USERAGENT, 'cURL PHP');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$this->data = curl_exec($curl);
curl_close($curl);
return $this; //make it a chainable method
}
/** Parse result data **/
function parse(){
$result = array();
$count = 0;
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($this->data);
$xpath = new DOMXPath($dom);
$news = $xpath->query('//td[#bgcolor="#DDDDDD"]/table/tr[position()=2]/td[position()=2]');
foreach( $news as $n){
$result[] = $n->nodeValue;
$count++;
if ($count >9)
break; //we just need 10 results. Index starts from 0
}
return $result;
}
}
error_reporting(0);
$dse = new CURL_CRAWLER('http://www.dsebd.org/display_news.php');
echo "<pre>";
print_r( $dse->crawl()->parse() );
echo "<pre>";
?>
Your syntax error is that you should use explicit "greater than" sign instead of HTML entities > - server doesn't need those, it is not a browser that can render it correctly. Just change:
print_r( $dse->crawl()->parse() );
^^^^ ^^^^
to:
print_r( $dse->crawl()->parse() );

How can I get the data from JSON code with PHP?

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 );
}
}
?>

Categories