I'm trying to display the CSV file data, which is inside of the gz file.
My code is:
$file = file("compress.zlib://".$filePath);
foreach($file as $line){
list($lid,$lname,$lrevenue,$ctr) = explode(",", $line);
print $lid ." | ". $lname ." | ". $lrevenue ." | ". $ctr . "\n";
}
This code works but I don't know how to skip displaying the first row from it.
Thanks in advance.
$file = file("compress.zlib://".$filePath);
unset($file[0]);
foreach($file as $line){
list($lid,$lname,$lrevenue,$ctr) = explode(",", $line);
print $lid ." | ". $lname ." | ". $lrevenue ." | ". $ctr . "\n";
}
$file = file("compress.zlib://".$filePath);
$i=0;
foreach($file as $line){
if($i == 0) continue;
list($lid,$lname,$lrevenue,$ctr) = explode(",", $line);
print $lid ." | ". $lname ." | ". $lrevenue ." | ". $ctr . "\n";
$i++;
}
Related
When I import XLS files, I would like to avoid the import of empty rows. I tried with several codes without success. Can anyone help me?
This is the code:
require('xls/php-excel-reader/excel_reader2.php');
require('xls/SpreadsheetReader.php');
require_once '_inc/_db.php';
$r = rand();
$mimes = ['application/vnd.ms-excel', 'text/xls', 'text/xlsx', 'application/vnd.oasis.opendocument.spreadsheet'];
if (in_array($_FILES["file"]["type"], $mimes)) {
$uploadFilePath = 'storage/' . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath);
rename($uploadFilePath, "storage/" . $r . ".xls");
$uploadFilePath = "storage/" . $r . ".xls";
$Reader = new SpreadsheetReader($uploadFilePath);
$totalSheet = count($Reader->sheets());
$tot = 0;
/* For Loop for all sheets */
for ($i = 0; $i < $totalSheet; $i++) {
$Reader->ChangeSheet($i);
$tots = $totalSheet;
foreach ($Reader as $Row) {
$tot++;
$nrcontenitore = isset($Row[0]) ? $Row[0] : '';
$nrcontenitore = str_replace(".", "", $nrcontenitore);
$nrcontenitore = str_replace("-", "", $nrcontenitore);
$nrcontenitore = str_replace("_", "", $nrcontenitore);
$nrcontenitore = str_replace("/", "", $nrcontenitore);
$nrcontenitore = str_replace("\'", "", $nrcontenitore);
$nrcontenitore = preg_replace('/\s+/', '', $nrcontenitore);
$nrcontenitore = isset($Row[0]) ? $Row[0] : '';
$data = isset($Row[1]) ? $Row[1] : '';
$doc .= formatcontainernr(strtoupper($nrcontenitore)) . " | " . date("d/m/Y", strtotime($data)) . "\n";
$docarr .= formatcontainernr(strtoupper($nrcontenitore)) . " | " . date("d/m/Y", strtotime($data)) . "#\n";
}
}
}
I would like to import a XLS file with no empty rows.
try to add a checking if the row is empty
foreach ($reader as $row) {
if($row == null){
continue;
}
}
I have a text file generated from our banking software which looks like this:
This is my code to print the text file contents line by line:
<?php
$myFile = "20151231.txt";
$lines = file($myFile);
foreach ($lines as $line_num) {
echo htmlspecialchars($line_num)."<br>";
}
It prints like this:
I just want each line that starts with:
====>
I want everything else deleted.
I tried a lot but failed to print lines with the columns separated as it looks in the text file image.
This is how I want each line to print:
====>0518 Intt on Consumer Loan 401010707 108,149.00
Your assistance regarding this will be highly appreciated.
You can print it as a table:
<?php
$myFile = "20151231.txt";
$lines = file($myFile);
echo '<table>';
foreach ($lines as $line_num) {
if (strpos($line_num, '====>') !== false) {
$str = trim(htmlspecialchars($line_num));
echo '<tr>';
echo '<td>' . getColumnText("/====>\d+/", $str) .'</td>';
echo '<td>' . getColumnText("/\s([a-zA-Z\s]+)/", $str) .'</td>';
$secondCol = getColumnText("/\s([0-9]+)/", $str);
echo '<td>' . $secondCol .'</td>';
$thirdCol = end(explode(" ", $str));
if (trim($secondCol) === $thirdCol) {
echo '<td style="text-align:right">' . str_repeat(" ", 10) .'</td>';
} else {
echo '<td style="text-align:right">' . str_repeat(" ", 10) . $thirdCol .'</td>';
}
echo '</tr>';
}
}
echo '</table>';
function getColumnText($pattern, $str) {
preg_match($pattern, $str, $matches);
return trim(current($matches));
}
yes you can do that with strpos or regularexpression and i am just writing code using strpos
<?php $myFile = "text.txt";
$lines = file($myFile);
echo '<table cellspacing="20">';
$linenum = 1;
foreach ($lines as $line_num) {
echo '<tr>';
// check whether line conatain ====>, if you want to check starting of line then just put 0 instead of false in following condition
if(strpos($line_num,'====>')!==false)
{
$texts= substr($line_num, strpos($line_num,'====>')+5);
$textarr = explode(" ", $texts);
echo '<td>'.$linenum.'</td>';
foreach($textarr as $arr)
{
echo '<td>'.$arr.'</td>';
}
$linenum++;
//print_r($textarr);
//echo htmlspecialchars($line_num)."<br>";
}
}
echo '<table>';
I am trying to create a cron job in php that deletes disabled users found in a csv file and logs the deleted users to a txt file. Everything works except only the last user in the csv file is deleted. Here is what I have so far:
class purgeInactive extends JApplicationCli
{
public function doExecute()
{
$file = '../tmp/purge_user.csv';
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csvRows = array_map('str_getcsv', $contents);
$log = ('../log/purged_users.txt');
$today = date('F j, Y, g:ia');
$row = 1;
if (($handle = fopen("../tmp/purge_user.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
file_put_contents($log, PHP_EOL . 'Removed Disabled User(s): ' . $data[$c] . PHP_EOL . '-' . $today . PHP_EOL, FILE_APPEND);
$disUsers = implode(',', $data);
echo ', ' . $disUsers ; // to test $disUsers output
} // end for statement
} // end while statment
} // end if statement
fclose($handle);
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$userArray = var_export($disUsers,true);
echo PHP_EOL.'This is to test the output of $userArray'.$userArray;
$query
->select($db->quoteName(array('id')))
->from($db->quoteName('#__users'))
//->delete ($db->quoteName('#__users'))
//->where(array($db->quoteName('username') . ' IN(' . $userArray) . ')');
->where(array($db->quoteName('username') . ' = ' . $userArray));
//->where($deleteReq);
$db->setQuery($query);
//$result = $db->execute();
$result = $db->query();
}
}
JApplicationCli::getInstance('purgeInactive')->execute();
Any suggestions on how to run each user in the csv file individually? I am about brain dead on this as I have been working on it too long.
Note: I am running Joomla that uses ldap and I use echo for $userArray to check results.
I think instead of ...
->where(array($db->quoteName('username') . ' = ' . $userArray));
You just want
->where(array($db->quoteName('username') . ' IN(' . $userArray) . ')');
That's assuming you want to delete all the rows whose usernames are in $userArray.
If the values in $userArray aren't necessarily SQL-safe, you might also want to do this first:
$userArray = array_map('mysql_real_escape_string', $userArray);
Each row of your csv is iterating this line: $disUsers = implode(',', $data);
This means that all usernames in that row will be saved to $disUsers, then the next iteration will overwrite the old data with the new row's usernames -- this is why only the final row of data is making it down to your delete query.
$data[$c] is what should be pushed into a $disUsers array like this: $disUsers[] = $data[$c];
In your query, you'll need to quote-wrap each array value; this will do that job:
->where($db->qn('username') . ' IN (' . implode(',', array_map(function($username)use($db) {return $db->q($username);}, $disUsers)) . ')')
Here is a post of mine where I discuss writing Joomla queries with IN: https://joomla.stackexchange.com/a/22898/12352
I am totally lost here, I made a text file with names in it. I would like to assign a array to each name and open it into a php file for displaying on a webpage so I can change things, I just cannot for the life of me figure this out.
$lines = file('responders.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line_num => $line)
{
print "<input type='checkbox' name='responders[]' value='" . $line_num . "' >" . $line . " " . $line_num . "<br />\n";
}
My text file just has names example
Jon
Jim
Tim
Tom
Jerry
I would like to assign an array somehow to basically say
4 Jon
5 Jim
17 Tim
47 Tom
52 Jerry
Without having to use a bunch of white space per line. Is it at all possible? Thanks.
In the end I would like to read my mysql database find out whos all listed and put a check mark next to people who is in the mysql field. I used Implode for that if that helps anybody.
If combine wouldn't work for you you could just explicitly declare the array k/v.
$lines = file('responders.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nameArray = array();
$i = 0;
foreach ($lines as $line)
{
echo $i . " > " . $line . "\n";
$nameArray[i] = $line;
$i++;
}
There is a more easy way to achieve this:
$content = file_get_contents("responders.txt");
if(strlen($content) > 0) {
$myData= explode(" ", $content);
if(count($myData) > 0) {
$c = 1;
foreach($myData as $value) {
echo $value . " -> ";
if($c % 2 == 0) {
echo "<br />";
}
$c++;
}
}
}
<?php
header("Content-type: text/plain");
$GLOBALS["db_name"] = "fggff_highscores";
$GLOBALS["table_name"] = "testing";
$GLOBALS["view_user"] = "fgfggg_players";
$GLOBALS["view_pass"] = "removed";
$username = strip_tags($_GET["player"]);
$fileContents = #file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=" . $username);
echo $fileContents;
if ($fileContents == FALSE) {
die("PLAYER NOT FOUND");
}
//$content = array();
$data = explode("\n", $fileContents);
/*
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
*/
$stats0 = explode(",", $data[0]);
echo "\n";
echo "\n";
echo "Overall Rank: " .number_format($stats0[0]);
echo "\n";
echo "Total Level: " .number_format($stats0[1]);
echo "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
$stats1 = explode(",", $data[1]);
echo "\n";
echo "\n";
echo "Attack Rank: " .number_format($stats1[0]);
echo "\n";
echo "Attack Level: " .number_format($stats1[1]);
echo "\n";
echo "Attack XP: " .number_format($stats1[2]);
$stats2 = explode(",", $data[2]);
echo "\n";
echo "\n";
echo "Defence Rank: " .number_format($stats2[0]);
echo "\n";
echo "Defence Level: " .number_format($stats2[1]);
echo "\n";
echo "Defence XP: " .number_format($stats2[2]);
?>
Example above should be working when ran you can use this player to see output -- .php?player=zezima
The output of each $data[0] is something like--------53,2496,1661657944
53-----------------------number_format($stats0[0])
2,496--------------------number_format($stats0[1])
1,661,657,944------------number_format($stats0[2])
--
Then I'm trying to break up each $data[] index into 3 pieces, the way I have it above works but I want to be able to do something like a for each loop to go through each $data[] indexes and break each up using explode(",", $data[0]); explode(",", $data[1]); explode(",", $data[2]); but it would have the index increment each time. What I need in the end is each value to be in a variable that I can use. Example:
$apple = number_format($stats0[0]);
echo $apple;
This is what I've tried something with:
$content = array();
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
instead of repeating yourself again and again, create a function like this one:
function print($data, $i){
$stats0 = explode(",", $data[$i]);
echo "\n\nOverall Rank: " .number_format($stats0[0]) . "\n";
echo "Total Level: " .number_format($stats0[1]) . "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
}
and call it in a loop.