PHP Outputting results based on greater than/less than from JSON - php

I am trying to get this script to output results based on a greater than/less than script. When I run this script all it does it output the first line in the text file. Any suggestions as to what I am missing?
<?php
$lines = file('unique.txt'); // Reads the file with the list of user numbers
$timestamp = time(); // Defines time for below renaming
foreach ($lines as $usernumber) { // Loops line by line
$link = 'http://backpack.tf/api/IGetUsers/v2/?&steamids=' . $usernumber . '&format=json';
$json = file_get_contents($link); // Reads link (this ^)
$data = json_decode($json); // Defines decode as json
if (!empty($data)) {
$profiles = array(); //init array so we can use $profiles[] later
foreach ($data->response->players as $player) { // Loop thrugh all the players
$player2 = $player->backpack_value;
if ($player2 < 9999999) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
var_dump($profiles); // Dump the array to browser for debugning
$fh = fopen("final." . $timestamp . ".txt", 'a') or die("can't open file"); // Opens final.txt to write in
fwrite($fh, $usernumber); // Writes the parsed results to final.txt
} //closes if $playtime
} //closes foreach $data
} //closes if !empty
else {
echo $data;
}
} //closes foreach $lines
?>
Unique.txt contains
76561197992831594
76561197992707820
76561197992146126
76561197992694522
76561197992707820
76561197992831594
JSON Example
{
"response": {
"success": 1,
"current_time": 1369685515,
"players": {
"0": {
"steamid": "76561197992831594",
"success": 1,
"backpack_value": 47.97,
"backpack_update": 1369683750,
"name": "WesFox13",
"notifications": 0
}
}
}
}

Okay There is two fundamental problems.
The fopen call needs to move outside of the loop.
the file call has an annoying habit of keeping the trailing newline. When you are building up your url you should use trim($usernumber) to get rid of it.
Here is an update with those two things in place.
<?php
$lines = file('unique.txt'); // Reads the file with the list of user numbers
$timestamp = time(); // Defines time for below renaming
$fh = fopen("final." . $timestamp . ".txt", 'a') or die("can't open file"); // Opens final.txt to write in
foreach ($lines as $usernumber) { // Loops line by line
$link = 'http://backpack.tf/api/IGetUsers/v2/?&steamids=' . trim($usernumber) . '&format=json';
$json = file_get_contents($link); // Reads link (this ^)
$data = json_decode($json); // Defines decode as json
print_r($json);
if (!empty($data)) {
$profiles = array(); //init array so we can use $profiles[] later
foreach ($data->response->players as $player) { // Loop thrugh all the players
$player2 = $player->backpack_value;
if ($player2 < 9999999) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
var_dump($profiles); // Dump the array to browser for debugning
fwrite($fh, $usernumber); // Writes the parsed results to final.txt
} //closes if $playtime
} //closes foreach $data
} //closes if !empty
else {
echo $data;
}
} //closes foreach $lines

I've done this with CURL and it works too.
The code:
$lines = array('76561197992831594','76561197992707820','76561197992146126');
$timestamp = time(); // Defines time for below renaming
foreach ($lines as $usernumber) { // Loops line by line
$link = 'http://backpack.tf/api/IGetUsers/v2/?&steamids=' . $usernumber . '&format=json';
$json = curl_download($link); // Reads link (this ^)
$data = json_decode($json); // Defines decode as json
if (!empty($data)) {
$profiles = array(); //init array so we can use $profiles[] later
foreach ($data->response->players as $player) { // Loop thrugh all the players
$player2 = $player->backpack_value;
if ($player2 < 9999999) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
var_dump($profiles); // Dump the array to browser for debugning
file_put_contents("final." . $timestamp . ".txt", $usernumber);
} //closes if $playtime
} //closes foreach $data
} //closes if !empty
else {
echo $data;
}
}
curl download function:
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.google.pl");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla Firefox/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
Output:
array(1) { [0]=> object(stdClass)#102 (6) { ["steamid"]=> string(17) "76561197992831594" ["success"]=> int(1) ["backpack_value"]=> float(47.97) ["backpack_update"]=> int(1369683750) ["name"]=> string(8) "WesFox13" ["notifications"]=> int(0) } } array(1) { [0]=> object(stdClass)#106 (6) { ["steamid"]=> string(17) "76561197992707820" ["success"]=> int(1) ["backpack_value"]=> float(59.78) ["backpack_update"]=> int(1369689171) ["name"]=> string(10) "Alexsutton" ["notifications"]=> int(0) } } array(1) { [0]=> object(stdClass)#98 (6) { ["steamid"]=> string(17) "76561197992146126" ["success"]=> int(1) ["backpack_value"]=> float(36181.59) ["backpack_update"]=> int(1369689000) ["name"]=> string(25) ":HIT: Bobo the Monkey Boy" ["notifications"]=> int(0) } }
My suggestion to you is to use CURL when you want to download something from Web. Moreover use file_get_contents() and file_put_contents() syntax is short and they do the same and they are easier to use.

Related

Wordpress admin_post or run a file from plugin

I want to know if you can help me to get wordpress to do the same as when I just open the file online using the url and not through a function like
add_action( 'admin_post_uploadImage', 'uploadImage' );
Is there a way I can do that.
It says: fopen(uploads/916224322.jpg): failed to open stream: No such file or directory in ********\wp-content\plugins\tandhjuletodderapi\functions.php on line 135
[31-Jul-2022 16:19:09 UTC] PHP Warning: curl_setopt(): supplied argument is not a valid File-Handle resource in
Is it something else that makes it not able to.
Have looked at chmod and it works as it should. it works fine when I don't run it from a function but just through the file without any post submit.
What I had thought if I could now set the file to perform that job, without being able to open the file without an admin process
Hope it makes sense.
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 1300);
function uploadImage()
{
if (isset($_POST['submitUploadImage'])) {
if (!current_user_can('manage_options')) {
echo 'Fejl du har ikke ret til at gøre denne handling';
exit;
}
if (!wp_verify_nonce($_POST['UploadBilleder_nonce'], 'UploadBilleder_nonce')) {
wp_die('Validering fejlede!!');
} else {
function multiple_download(array $urls, $save_path = 'uploads')
{
$multi_handle = curl_multi_init();
$file_pointers = [];
$curl_handles = [];
foreach ($urls as $key => $url) {
$file = $save_path . '/' . basename($url);
if(!is_file($file)) {
$curl_handles[$key] = curl_init($url);
$file_pointers[$key] = fopen($file, "x");
curl_setopt($curl_handles[$key], CURLOPT_FILE, $file_pointers[$key]);
curl_setopt($curl_handles[$key], CURLOPT_HEADER, 0);
curl_setopt($curl_handles[$key], CURLOPT_CONNECTTIMEOUT, 60);
curl_multi_add_handle($multi_handle,$curl_handles[$key]);
}
}
// Download the files
do {
curl_multi_exec($multi_handle,$running);
} while ($running > 0);
foreach ($urls as $key => $url) {
curl_multi_remove_handle($multi_handle, $curl_handles[$key]);
curl_close($curl_handles[$key]);
fclose ($file_pointers[$key]);
}
curl_multi_close($multi_handle);
}
$getFunction = new TandhjuletCSV;
$getData = $getFunction->getImageToUpload();
$getUrl = array();
$count = 0;
foreach ($getData as $key => $values) {
$count++;
$getUrl[] = $values;
if(count($getData) == $count) {
break;
}
}
multiple_big_download($getUrl);
multiple_download($getUrl);
}
wp_redirect(admin_url('options-general.php?page=cykel_visning'));
}
}
add_action( 'admin_post_uploadImage', 'uploadImage' );
Best regards
Morten

Duplicate detection code not working

I have a fairly simple piece of code here, i just add a bunch of links in the database, then check each link for a 200 ok.
<?php
function check_alive($url, $timeout = 10) {
$ch = curl_init($url);
// Set request options
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_NOBODY => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_USERAGENT => "page-check/1.0"
));
// Execute request
curl_exec($ch);
// Check if an error occurred
if(curl_errno($ch)) {
curl_close($ch);
return false;
}
// Get HTTP response code
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Page is alive if 200 OK is received
return $code === 200;
}
if (isset($_GET['cron'])) {
// database connection
$c = mysqli_connect("localhost", "paydayci_gsa", "", "paydayci_gsa");
//$files = scandir('Links/');
$files = glob("Links/*.{*}", GLOB_BRACE);
foreach($files as $file)
{
$json = file_get_contents($file);
$data = json_decode($json, true);
if(!is_array($data)) continue;
foreach ($data as $platform => $urls)
{
foreach($urls as $link)
{
//echo $link;
$lnk = parse_url($link);
$resUnique = $c->query("SELECT * FROM `links_to_check` WHERE `link_url` like '%".$lnk['host']."%'");
// If no duplicate insert in database
if(!$resUnique->num_rows)
{
$i = $c->query("INSERT INTO `links_to_check` (link_id,link_url,link_platform) VALUES ('','".$link."','".$platform."')");
}
}
}
// at the very end delete the file
unlink($file);
}
// check if the urls are alive
$select = $c->query("SELECT * FROM `links_to_check` ORDER BY `link_id` ASC");
while($row = $select->fetch_array()){
$alive = check_alive($row['link_url']);
$live = "";
if ($alive == true)
{
$live = "Y";
$lnk = parse_url($row['link_url']);
// Check for duplicate
$resUnique = $c->query("SELECT * FROM `links` WHERE `link_url` like '%".$row['link_url']."%'");
echo $resUnique;
// If no duplicate insert in database
if(!$resUnique->num_rows)
{
$i = $c->query("INSERT INTO links (link_id,link_url,link_platform,link_active,link_date) VALUES ('','".$row['link_url']."','".$row['link_platform']."','".$live."',NOW())");
}
}
$c->query("DELETE FROM `links_to_check` WHERE link_id = '".$row['link_id']."'");
}
}
?>
I'm trying not to add duplicate urls to the database but they are still getting in, have i missed something obvious with my code can anyone see? i have looked over it a few times, i can't see anything staring out at me.
If you are trying to enforce unique values in a database, you should be relying on the database itself to enforce that constraint. You can add an index (assuming you are using MySQL or a variant, which the syntax appears to be) like this:
ALTER TABLE `links` ADD UNIQUE INDEX `idx_link_url` (`link_url`);
One thing to be aware of is extra spaces as prefixes/suffixes so use trim() on the values and also, you should strip trailing slashes to keep everything consistent (so you don't get dupes) using rtrim().

Parsing Inconsistent JSON data: PHP

The application Pipedrive gives me inconsistent json data. For example, in some array elements, it gives me "formatted_value":"$3,500","weighted_value":2100,"formatted_weighted_value":"$2,100","rotten_time":null, while in others, it gives me, "formatted_value":"$2,950","rotten_time":null,"weighted_value":2950,"formatted_weighted_value":"$2,950". I would like the json data to be in the order of formatted_value,weighted_value,formatted_weighted_value,rotten_time in every array element, but that's not the case sadly.
Does anyone know of a way to check that the right data is written the right column based on column name and key name?
Below is my code to parse the json data:
function parseFunction($startPos) {
$url = 'urlToCallJsonData';
$ch = curl_init($url); //initialize connection with a URL
if(is_callable('curl_init'))
{
echo "Enabled";
}
else
{
echo "Not enabled";
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");
$json_response = curl_exec($ch);
$info = curl_getinfo($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( $status != 200 )
{
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
}
curl_close($ch);
$response = json_decode($json_response, true);
$count = Count($response['data']);
for ($x=0; $x<$count; $x++)
{
$currentRecord = $response['data'][$x];
}
//open writing to file
if($startPos == 0)
{
$fp = fopen('cacheDeals.csv', 'w');
}
else
{
$fp = fopen('cacheDeals.csv', 'a');
}
$test_array = $response['data'][0];//test_array = first row of data
// writes the headers to the csv file.
if($startPos == 0)
{
$keys = array_keys($test_array);
fputcsv($fp, $keys);
}
$array_records = $response['data'];//all of incoming data
//write data to csv file
foreach ($array_records as $fields)
{
fputcsv($fp, $fields);
}
//check to see if more data should be written
$more = $response[additional_data][pagination][more_items_in_collection];
$nextStart = $response[additional_data][pagination][next_start];
if($more =="true")
{
downloadPipedriveDealsData($nextStart);
}
}//end of function
parseFunction(0);
Sorry but I cant point this out in comments alone, some of this could be cleaner such as
//open writing to file
if($startPos == 0)
{
$fp = fopen('cacheDeals.csv', 'w');
}
else
{
$fp = fopen('cacheDeals.csv', 'a');
}
$test_array = $response['data'][0];//test_array = first row of data
// writes the headers to the csv file.
if($startPos == 0)
{
$keys = array_keys($test_array);
fputcsv($fp, $keys);
}
Could be simply this
// writes the headers to the csv file.
if($startPos == 0){
$fp = fopen('cacheDeals.csv', 'w');
fputcsv($fp, array_keys($response['data'][0]));
}else{
$fp = fopen('cacheDeals.csv', 'a');
}
I don't see a purpose to this whole block at all
$count = Count($response['data']);
for ($x=0; $x<$count; $x++)
{
$currentRecord = $response['data'][$x];
}
This syntax is invalid
$more = $response[additional_data][pagination][more_items_in_collection];
$nextStart = $response[additional_data][pagination][next_start];
And will issue a Notice ( undefined constant assuming '' ) etc. because there are no quotes around the string keys in the arrays. In the unlikly event that one of those keys is a constant, that's a whole other can of worms. Because you will never get your data out then. They should be done this way with ' or " 's around them. see also What does the PHP error message "Notice: Use of undefined constant" mean?
$more = $response['additional_data']['pagination']['more_items_in_collection'];
$nextStart = $response['additional_data']['pagination']['next_start'];
Just saying.

how to parse m3u8 and get difffrent bitttrate sub m3u8 urls?

could any one show me how in php i can get different bitrate(resolution) sub m3u8 urls if we have the main playlist m3u8 using get_data method?The following is data i have from get_data method but i want to get m3u8 urls for each resolution. Could any one show me how this can be done?Thanks in advance.
$returned_content = get_data(''.$m3u8Url);
/* gets the data from a URL */
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
main playlist m3u8:
#EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1628000,RESOLUTION=852x480,CODECS="avc1.77.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/erewewrwrtf34324343443243434344/test1.mpegts/playlist-dfasdfasdfaw4q3243241.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=128000,RESOLUTION=256x144,CODECS="avc1.66.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/fgdhgfhgjhghfdsdf45454545345435/test1.mpegts/playlist-adfdfghgjdt5t45454542.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=464000,RESOLUTION=426x240,CODECS="avc1.77.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/764563564565445fsdf4r3dfdfdffdf/test1.mpegts/playlist-eertyeryry564534rrtr3.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=828000,RESOLUTION=640x360,CODECS="avc1.77.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/fgsfdgdfgfdg5435345456745264554/test1.mpegts/playlist-fgsfghdghjt4353454544.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2128000,RESOLUTION=1024x576,CODECS="avc1.77.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/sfdgsdfgfdgfdgfdgfd465436546576/test1.mpegts/playlist-fghdjhygjujdfgsaf4455.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=3692000,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/sfdghgjyuktyurty546565466453645/test1.mpegts/playlist-safdghhgfjjyj45345546.m3u8
First off, you need to get data source, then process them (explode() the values, as your sample data is in line breaks), then group them by two's, and in the end loop them. Consider this example:
<?php
$curl_output = '#EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1628000,RESOLUTION=852x480,CODECS="avc1.77.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/erewewrwrtf34324343443243434344/test1.mpegts/playlist-dfasdfasdfaw4q3243241.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=128000,RESOLUTION=256x144,CODECS="avc1.66.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/fgdhgfhgjhghfdsdf45454545345435/test1.mpegts/playlist-adfdfghgjdt5t45454542.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=464000,RESOLUTION=426x240,CODECS="avc1.77.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/764563564565445fsdf4r3dfdfdffdf/test1.mpegts/playlist-eertyeryry564534rrtr3.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=828000,RESOLUTION=640x360,CODECS="avc1.77.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/fgsfdgdfgfdg5435345456745264554/test1.mpegts/playlist-fgsfghdghjt4353454544.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2128000,RESOLUTION=1024x576,CODECS="avc1.77.30,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/sfdgsdfgfdgfdgfdgfd465436546576/test1.mpegts/playlist-fghdjhygjujdfgsaf4455.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=3692000,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"
http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/sfdghgjyuktyurty546565466453645/test1.mpegts/playlist-safdghhgfjjyj45345546.m3u8';
// process the string
$pieces = explode("\n", $curl_output); // make an array out of curl return value
unset($pieces[0]); // remove #EXTM3U
$pieces = array_map('trim', $pieces); // remove unnecessary space
$pieces = array_chunk($pieces, 2); // group them by two's
?>
Formatted pieces should look something like this:
Array
(
[0] => Array
(
[0] => #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1628000,RESOLUTION=852x480,CODECS="avc1.77.30,mp4a.40.2"
[1] => http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/erewewrwrtf34324343443243434344/test1.mpegts/playlist-dfasdfasdfaw4q3243241.m3u8
)
[1] => Array
(
[0] => #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=128000,RESOLUTION=256x144,CODECS="avc1.66.30,mp4a.40.2"
[1] => http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/fgdhgfhgjhghfdsdf45454545345435/test1.mpegts/playlist-adfdfghgjdt5t45454542.m3u8
)
...
Then, on the html loop and them, and inside the loop process the links:
<?php foreach($pieces as $key => $value): ?>
<a href="<?php echo $value[1]; ?>">Watch this in
<?php
$value[0] = explode(',', $value[0]);
foreach($value[0] as $index => $element) {
if(stripos($element, 'RESOLUTION') !== false) {
echo $element;
}
}
?>
</a><br/>
<?php endforeach; ?>
The HTML Markup should now look something like this:
<a href="http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/erewewrwrtf34324343443243434344/test1.mpegts/playlist-dfasdfasdfaw4q3243241.m3u8">Watch this in
RESOLUTION=852x480 </a>
<a href="http://me.mysite.com/media/l3/ertetertyrtut34534234324f3esrere/fgdhgfhgjhghfdsdf45454545345435/test1.mpegts/playlist-adfdfghgjdt5t45454542.m3u8">Watch this in
RESOLUTION=256x144 </a>
If I understood the quetion right you need to parse a string and get resolution.
function findResolution($string){
$array = explode(",",$string);
foreach ($array as $item){
if (strpos($item,"RESOLUTION")!==false){
return str_replace("RESOLUTION=","",$item);
}
}
}
Why not fopen/fgets?
function parseHLS($file) {
$return = array();
$i = 0;
$handle = fopen($file, "r");
if($handle) {
while(($line = fgets($handle)) !== FALSE) {
if(strpos($line,"EXT-X-STREAM-INF") !== FALSE) {
if ($c=preg_match_all ("/.*?(BANDWIDTH)(.*?)(,)(RESOLUTION)(.*?)(,)/is", $line, $matches)) {
$return['data'][$i]['bandwidth'] = str_replace("=","",$matches[2][0]);
$return['data'][$i]['resolution'] = str_replace("=","",$matches[5][0]);
}
}
if(strpos($line,".ts") !== FALSE) {
$return['data'][$i]['url'] = str_replace(array("\r","\n"),"",$line);
$i++;
}
}
fclose($handle);
}
return $return;
}
That gets you an array with bandwidth, resolution and url keys for each iteration in the original file.

PHP - Foreach loop only echoing first letter of string

I have an array that looks like this:
array(1) {
["brookybear"]=> array(5) {
["id"]=> int(20217894)
["name"]=> string(10) "Brookybear"
["profileIconId"]=> int(603)
["summonerLevel"]=> int(30)
["revisionDate"]=> float(1397388011000)
}
}
when i var_dump(); it. I'm trying to use a foreach loop to take the "name" value out of it. However, when I echo it, I only get "B" as the output, and not the full Brookybear.
Here is my foreach loop:
$url="APIURL";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
$array = json_decode($result, true);
foreach($array['brookybear'] as $champs)
{
echo $champs['name'];
}
Looks like you're looping on the 'brookybear' item instead of the parent array.
If you want to see all the names of all the $champs:
$array = json_decode($result, true);
foreach($array as $champs)
{
echo $champs['name'];
}
or more clearly:
$champions = json_decode($result, true);
foreach($champions as $champ)
{
echo $champ['name'];
}
Why do you use loop to get the value? If I am doing this, I will simply write:
<?php
if ( isset( $array['brookybear']['name'] ) ) {
echo $array['brookybear']['name'];
}
If first character is only display in string, you know what is the reason i now,
make sure array variable name is not same in your above script
. example
$my_var = "My name is umair";
and below you same use this variable for array
$my_var[0] = "My name is umair";
now if you echo array var it will show only first letter in output is "M"
simply change the array variable than it will be working

Categories