Weird characters jump out of arrays when used with get file contents - php

Hi this is a portion of my code which when ever output, the array $data2[0] seems to always output weird characters. It doesn't happens in $data2[1] or $data[2]..??? I been trying to figure this out for 2 days.
<?php
$filename = "../file/attendance_log/1414001189.txt";
$contents = file_get_contents($filename);
$contents = str_replace("\"","",$contents);
$lines = explode("\n", $contents);
$numrows = count($lines);
$x = 0;
for ($numrows; $x < $numrows; $x++)
{
echo $data2[0];
$data2 = explode(",", $lines[$x]);
echo $time = mktime(0,0,1,$data2[1],$data2[0],$data2[2]);
$user_no = $data2[3];
$item_no = $data2[4];
$quantity = $data2[5];
$waste = $data2[6];
$job_no = $data2[7];
}
?>

You're trying to explode and use the first line which has the column names in it
i slightly rewrote what you had to accomodate that and also not use a counter and
setting the default timezone too so you get what i think you were looking for
<?php
$filename = "../file/attendance_log/1414001189.txt";
$contents = file_get_contents($filename);
$contents = str_replace("\"","",$contents);
$lines = explode("\n", $contents);
date_default_timezone_set('UTC');
if (count($lines)){
$lines = array_slice($lines, 1);
foreach ($lines as $line){
$data2 = explode(",", $line);
if (count($data2) == 8){
echo $data2[0];
$time = mktime(0,0,1,$data2[1],$data2[0],$data2[2]);
echo $time . '<br>';
$user_no = $data2[3];
$item_no = $data2[4];
$quantity = $data2[5];
$waste = $data2[6];
$job_no = $data2[7];
}
}
}
?>

I had found the answer. It is because when the user save the file. It saved as Unicode UTF. It should save as Unicode UTF-8, that way there won't be any problems.

Related

(PHP, AJAX) Simple counter. Figured the problem, no solution

Apologies for having to ask.
In short I'm making a simple imageboard with a "like" button for each image. The number of clicks (likes) stores in 'counter.txt' file in the following format:
click-001||15
click-002||7
click-003||10
Clicking the buttons initiates a small php code via AJAX. counter.php:
<?php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
file_put_contents($file, $lines);
fclose($fh);
?>
So when I run the website and testclick my buttons I get the following message:
Notice: Undefined offset: 1 in C:\wamp64\www\wogue\counter.php on line
18
I figured that the script 'counter.php' creates a whitespace on a new string in 'counter.txt' and so it fails to 'explode' and thus make a [1] index. The way I figured that is by backspacing the last empty line in .txt file and saving it. It ran without errors until I clicked a button a few times then the same error appeared.
The piece of code in index looks like this:
<?php
$clickcount = explode("\n", file_get_contents('counter.txt'));
foreach($clickcount as $line){
$tmp = explode('||', $line);
$count[trim($tmp[0])] = trim($tmp[1]);
}
?>
Any ideas?..
Trim $line and if it is not empty - do what you need:
$line = trim(fgets($fh));
if ($line) {
$line = explode('||', $line);
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
Or check with empty this way:
$line = explode('||', fgets($fh));
if(!empty(line[0]) && !empty($line[1])){
if(line[0] == $id){
$line[1]++; // increment count by 1
echo $line[1];
}
$lines .= "{$line[0]}||{$line[1]}\r\n";
}
}
You are writing using \r\n as a line separator in counter.php and reading the same file exploding only for \n. You should be consistent.
Just removing the \n should be enough to avoid the extra "space" you're seeing.
<?php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\n"; //removing the \r here
}
}
file_put_contents($file, $lines);
fclose($fh);
?>

Read external file match specific string in first column and return respective string of second column in php

I have two text files, csvurl.txt and tickerMaster.txt
tickerMaster.txt
H0001
Remarks: No "H0003" in tickerMaster.txt and the number are not in sequence
csvurl.txt
H0001, URL1
H0003, URL3
I would like to read the entries in tickerMaster.txt one by one, say H0001, H0003...
and createURL by matching the data in csvurl.txt. So I am using following code...
<?php
function createURL($ticker){
$file = 'csvurl.txt';
header('Content-Type: text/plain');
$contents = file_get_contents($file);
$sep = ',';
$pattern = preg_quote($searchfor, '/');
$searchfor = $ticker;
$pattern = "/^($searchfor\w+)$sep.*$/m";
if (preg_match_all($pattern, $contents, $matches)){
echo implode($matches[0])."\n";
}
else{
echo "No matches found";
}
}
function getCSVFile($url, $outputFile){
$content = file_get_contents($url);
$content = str_replace("Date,Open,High,Low,Close,Volume,Adj Close", "", $content);
$content = trim($content);
file_put_contents($outputFile, $content);
}
function fileToDatabase($txtFile, $tableName){
$file = fopen($txtFile, "r");
while(!feof($file)){
$line = fgets($file);
$pieces = explode(",", $line);
$date = $pieces[0];
$open = $pieces[1];
$high = $pieces[2];
$low = $pieces[3];
$close = $pieces[4];
$volume = $pieces[5];
$amount_change = $close-$open;
$percent_change = ($amount_change/$open)*100;
$sql = "SELECT * FROM $tableName";
$result = mysql_query($sql);
if(!$result){
$sql2 = "CREATE TABLE $tableName (date DATE, PRIMARY KEY(date), open FLOAT, high FLOAT, low FLOAT, close FLOAT, volume INT, amount_change FLOAT, percent_change FLOAT)";
mysql_query($sql2);
}
$sql3 = "INSERT INTO $tableName (date, open, high, low, close, volume, amount_change, percent_change) VALUES ('$date','$open','$high','$low','$close','$volume', '$amount_change', '$percent_change')";
mysql_query($sql3);
}
fclose($file);
}
function main(){
$mainTickerFile = fopen("tickerMaster.txt", "r");
while(!feof($mainTickerFile)){
$companyTicker = fgets($mainTickerFile);
$companyTicker = trim($companyTicker);
$fileURL = createURL($companyTicker);
$companyTxtFile = "txtFiles/".$companyTicker.".txt";
getCSVFile($fileURL, $companyTxtFile);
fileToDatabase($companyTxtFile, $companyTicker);
}
}
main()
?>
However, what I got is the whole line on the information in csvurl.txt
for example:
No matches foundH0001,URL1H0003,URL3
My desired output is just:
URL1
Actually, I am looking for the function like vlookup in excel, but I cant search any solution for this kind of matching.
Thanks.
I suppouse data have not error, so don't do any test
$c1 = file('csvurl.txt');
$l = count($c1);
for ($i = 0; $i < $l; $i++) {
list($name,$url) = explode(',', $c1[$i]);
// making array $red['H001'] => 'URL1"
$red[trim($name)] = trim($url);
}
unset($c1);
$c = file('tickerMaster.txt');
$l = count($c);
for ($i = 0; $i < $l; $i++) {
$c[$i] = trim($c[$i]);
// If rule exists
if(isset($red[$c[$i]])) echo($red[$c[$i]]);
}

preg_match and loop don't work with the first array value

To import and verify emails I use this script, but I have a problem. The first email preg_match doesn't work. Do you have any ideas?
$arr_csvfields = array(email, name);
$lines = file('uploads/'.$file);
$dataline = array();
foreach ($lines as $line) {
$dataline[] = $line;
}
for($i = 0; $i < $alllines; $i++) {
$data = $datenzeilen[$i];
$csvdata = explode(';',$data);
$newdata = array_combine($arr_csvfields, $csvdata);
$emailadress = str_replace(array("\r\n","\n\r", "\n", "\r"),'',trim($newdata['email']));
if(preg_match("/^[a-zA-Z0-9_.-]+#[a-zA-Z0-9][a-zA-Z0-9-.]+\.([a-zA-Z]{2,6})$/",$emailadress) == true){
echo $emailadress;
}
}
If I make an echo $i.' - '.$emailadress in the loop. I see the first email but the first mail will not work. It allways says false or so. All other works. If I change in the csv the first and the second. It’s the self problem. So allways the ID 0 will not work.
There are a few issues I see. Here is my cleanup of your code:
$arr_csvfields = array('email', 'name');
$lines = file('uploads/'.$file);
$dataline = array();
foreach ($lines as $line) {
$dataline[] = $line;
}
for($i = 0; $i < $alllines; $i++) {
$data = $datenzeilen[$i];
$csvdata = explode(';',$data);
$newdata = array_combine($arr_csvfields, $csvdata);
$emailadress = str_replace(array("\r\n","\n\r", "\n", "\r"),'',trim($newdata['email']));
if(preg_match("/^[a-zA-Z0-9_.-]+#[a-zA-Z0-9][a-zA-Z0-9-.]+\.([a-zA-Z]{2,6})$/",$emailadress)){
echo $emailadress;
}
}
First you are setting this:
$arr_csvfields = array(email, name);
I assume you want email & name to be column headers. You can’t just place those words in there without quotes. PHP will interpret that as a constant if you do that I believe? Anyway I changed that to this:
$arr_csvfields = array('email', 'name');
I believe this $arr_csvfields issue is the cause of the first e-mail failing.
Also, you do a check with your preg_match like this:
if(preg_match("/^[a-zA-Z0-9_.-]+#[a-zA-Z0-9][a-zA-Z0-9-.]+\.([a-zA-Z]{2,6})$/",$emailadress) == true){
There is no reason for the preg_match to have the == true. The condition action itself will handle that. So I changed that to this:
if(preg_match("/^[a-zA-Z0-9_.-]+#[a-zA-Z0-9][a-zA-Z0-9-.]+\.([a-zA-Z]{2,6})$/",$emailadress)){
That said, I still don’t understand what $arr_csvfields is for. So I recommend you change this line:
$newdata = array_combine($arr_csvfields, $csvdata);
To this:
$newdata = $csvdata;
Or perhaps change these two lines:
$newdata = array_combine($arr_csvfields, $csvdata);
$emailadress = str_replace(array("\r\n","\n\r", "\n", "\r"),'',trim($newdata['email']));
To this:
// $newdata = array_combine($arr_csvfields, $csvdata);
$emailadress = str_replace(array("\r\n","\n\r", "\n", "\r"),'',trim($csvdata['email']));
I am dancing around the issue of $newdata, $arr_csvfields & $csvdata because I do not know the logic of your logic code, but it’s the best I can do without having to rewrite the rest of your code. I also do not understand what $alllines is or even what $dataline is. But here is another chunk of code to test based on this:
$arr_csvfields = array('email', 'name');
$lines = file('uploads/'.$file);
$dataline = array();
foreach ($lines as $line) {
$dataline[] = $line;
}
for($i = 0; $i < $alllines; $i++) {
$data = $datenzeilen[$i];
$csvdata = explode(';',$data);
// $newdata = array_combine($arr_csvfields, $csvdata);
$emailadress = str_replace(array("\r\n","\n\r", "\n", "\r"),'',trim($csvdata['email']));
if(preg_match("/^[a-zA-Z0-9_.-]+#[a-zA-Z0-9][a-zA-Z0-9-.]+\.([a-zA-Z]{2,6})$/",$emailadress)){
echo $emailadress;
}
}

echoing foreach loop

i have the following code
$contents = file_get_contents('folder/itemtitle.txt');
$fnamedata = file_get_contents('folder/fname.txt');
$fnamearray = explode("\n", $fnamedata);
$contents = explode("\n", $contents);
foreach ($contents as $key => $itemline)
{
}
foreach ($fnamearray as $key2 => $fname)
{
echo ($fname);
echo ($itemline);
}
what i want to do is to have the first line of each file echo so the output looks like
fname[0},itemline[0],fname[1],itemline[1]
what i am getting with the following is just this
fname[0],fname[1],fname[2].... ect
h
Assuming the indexes will always match:
$contents = file_get_contents('folder/itemtitle.txt');
$fnamedata = file_get_contents('/home/b1396hos/public_html/ofwgkta.co.uk/dd_folder/fname.txt');
$fnamearray = explode("\n", $fnamedata);
$contents = explode("\n", $contents);
for($i = 0; $i < count($contents); $i++)
{
echo $fnamearray[$i];
echo $contents[$i];
}
Since both arrays are simple, consecutive numeric indexed arrays, you can just use a for loop:
$l = max(count($fnamedata),count($contents));
for($i=0; $i<$l; $i++) {
$itemline = $contents[$i];
$fname = $fnamearray[$i];
// do stuff
}

how do I read this text file in pieces?

hi I need to read a text file and then explode it to two piece then match it with give name then dispay if it matches...so far the code I made is given below..but it doesnt work..can any one tell me what wrong is with this code??
$name = "thomas";
$filename = file("land.txt");
//$contents = fread($handle, filesize($filename));
for($i=0; $i<count($filename); $i++)
{
$string = explode(":", $filename[$i]);
if($name == $string[1])
$id = $string[0];
}
echo $id;
this case it should display "D1"; but it doesnt!!
content of "land.txt" file
D1:thomas
D6:benny
D7:alwyn
D25:mathew
D9:peter
Try
$filename = file("land.txt", FILE_IGNORE_NEW_LINES);
Or
$string = explode(":", trim($filename[$i]));
What is FILE_IGNORE_NEW_LINES
Over here
if($name == $string[1]) use if($name == trim($string[1])) .
Try this and let me know.
$name = 'thomas';
$content = file('land.txt');
$id = NULL;
foreach($content as $no => $line){
$array = explode(':', $line);
if($array[1] == $name)
$id = $array[0];
}
echo $id;

Categories