Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
im new to php/html and i don't even know if PHP has ability like that.
What i want to do is to select some text from input and save it to txt file.
I have a for which takes all text from it and saves to .txt file. But there is alot of not necessary text and it makes .txt file big and hardly readable.
This is what text i usually paste
# userid name uniqueid connected ping loss state
# 122 "bryerzavala" [U:1:167845174] 03:25 152 0 active
# 118 "zhabka" [U:1:12080791] 05:41 109 0 active
and the part i need is only [U:1:167845174] so it would be great is there is an way to make a non needed text trown away and the file save only [U:X:XXXXXXXXX] part.
There are some options to do what you want, it all depends on how the input text is formatted:
If the input text is always formatted the same way for every line, meaning uniqueid is going to be located in the same position you could use substr http://php.net/manual/en/function.substr.php
If the position of uniqueid varies on every line you could use a regular expression to extract the part of the text line you are looking for, in this case you could use preg_match http://php.net/manual/en/function.preg-match.php
here is a simple approach. may be you will like it
i'll use the example of file.txt you have provided to simulate the input data.
old.txt
# userid name uniqueid connected ping loss state
# 122 "bryerzavala" [U:1:167845174] 03:25 152 0 active
# 118 "zhabka" [U:1:12080791] 05:41 109 0 active
process.php
<?php
$file = file_get_contents('./test.txt', true);
// var_dump($file);//for debug
preg_match_all('/\[U:\d:\d+\]/',
$file,
$out, PREG_PATTERN_ORDER);
var_dump($out); //for debug
//save data in your file
$fp = fopen("incomming.txt", "w");
foreach ($out[0] as $key => $data) {
fwrite($fp, $data.PHP_EOL);
}
//close file
fclose($fp);
echo '<hr/>';
$lines = file('incomming.txt');
var_dump($lines);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello I am trying to make a script that is based on HTML post and basic PHP.
I have 1 input on HTML, and I have this PHP code:
<?php echo'h'?>
One of my friends said that if I changed the w to an it would create a new line so I changed it and it is still not working.
Basically what I am trying to do is that when they enter the text box any word, it writes that word to the text document, but the second time it won't create a new line, I just want to create a new line.
Here is my full code:
<?PHP
$file_handle = fopen("sample.txt", "r");
$file_contents = $_POST['f1'];
fwrite($file_handle, $file_contents);
fclose($file_handle);
print "file created and written to";
?>
There is also other seemingly simpler functions by the names: file_put_contents() and file_get_contents(), which could be used (in your case) to make things a little easier to handle. The Code below shows the use of file_put_contents() and it's kin: file_get_contents() to accomplish the task.
<?php
$fileName = "sample.txt";
// GET THE TEXT TYPED-IN BY THE USER...
// ONLY YOU KNOW THE WAY TO GET THIS VALUE BUT WE CAN ASSUME (FOR NOW)
// THAT IT IS COMING FROM THE POST VARIABLE AND HAS THE NAME: input
$input = isset($_POST['input']) ? $_POST['input'] : null;
// FIRST TRY TO SEE IF THE FILE EXIST, OTHERWISE CREATE IT
// HOWEVER; WITH JUST AN EMPTY CONTENT
if(!file_exists($fileName)){
file_put_contents($fileName, "");
}
// DO THE SAVING ONLY IF WE HAVE ANY INPUT (STRING) TO SAVE
if($input){
// GET THE CURRENT CONTENTS OF THE FILE...
$fileContent = file_get_contents($fileName);
// ADD THE INPUT TO THE CURRENT CONTENTS OF THE FILE (WITH A NEW LINE)
$fileContent .= "\n{$input}";
// SAVE THE MODIFIED CONTENT BACK AGAIN...
$bytesSaved = file_put_contents($fileName, $fileContent);
// IF THE FILE WAS SUCCESSFULLY WRITTEN... THEN...
// DISPLAY A MESSAGE TO THAT EFFECT
if($bytesSaved){
print "file created and written";
}
}
I assume you want to add the line that has been posted to a previously stored file? In that case your code would look like this:
$file_handle = fopen("sample.txt", "a"); // append to previous contents
$file_contents = $_POST['f1'] . "\r\n";
fwrite($file_handle, $file_contents);
fclose($file_handle);
print "Content has been appended.";
More about the different fopen() modes can be found in the documentation, chapter "modes" and more about escape sequences (like \r\n) can be found in the Strings chapter.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am playing a video game that exports statistics into a CSV file.
http://pastebin.com/FPzJ3Qz7
Row 5 are my headers/tables.
I have a PHP/MySQL database that stores the data...
My issue is, every time I need to delete the first 4 lines, and all the ones after line 498. Because I am only interested in the data in between.
The line numbers can change every time.
I can use Regex to match the part I need, but when I use file_get_contents, it removes the new lines, and makes one big string.
Ultimately my goal is, upload CSV to web server, run cron to load PHP script, parse out the CSV, then run SQL statements to read CSV and update/insert into the database.
Any suggestions?
If you use file() instead of file_get_contents(), you'll get an array with a value per each line of your code. From there onward, you could use array_search() to find where your delimiters are located, and then use array_splice() to land with the relevant portion of the data.
However, since you're already preg_match()ing the bulk and extracting the relevant portion, this is real easy. $entries = explode("\n", $bulk); will give you an array with a line of data on each.
Then you can iterate over your array and e.g. use explode(',', $entryline) to parse each data-string to an array. There's also str_getcsv(), but in your case you'll have to tick off the default enclosure, since your data is unenclosed. Then plug that into matching fields in your database.
MySQL can also directly import CSV data with something like: LOAD DATA INFILE '/scores.csv' INTO TABLE tbl_name FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' IGNORE 4 LINES; -- though you'd have to somehow get rid of the chunk in the end, this is for uniform CSV data.
[If you have working code where you're trying to solve this, add it to your question for more help.]
Instead of loading all the file (that uses memory for nothing), you can read the file line by line (as a stream) and build a generator function that returns the records you are interested by one by one. In this way you don't need to delete, you only need to use conditions and to select what you want. Example:
function getLineFromFileHandler($fh, $headers = false) {
// initializations
$sectionSeparator = str_repeat('-', 62);
$newline = "\r\n";
$sectionSeparatorNL = $sectionSeparator . $newline;
$rowSeparatorNL = ',' . $newline;
// skip title/subtitle (feel free to add a param to yield them)
$title = stream_get_line($fh, 4096, $sectionSeparatorNL);
$subtitle = stream_get_line($fh, 4096, $sectionSeparatorNL);
// get the field names
$fieldNamesLine = stream_get_line($fh, 4096, $rowSeparatorNL);
// return the records
if ($headers) {
$fieldNames = array_map('trim', explode(',', $fieldNamesLine));
while (($line = stream_get_line($fh, 4096, $rowSeparatorNL)) !== false &&
strpos($line, $sectionSeparator) === false)
yield array_combine($fieldNames, explode(',', $line));
} else {
while (($line = stream_get_line($fh, 4096, $rowSeparatorNL)) !== false &&
strpos($line, $sectionSeparator) === false)
yield explode(',', $line);
}
}
$fh = fopen('csv.txt', 'r');
foreach(getLineFromFileHandler($fh, true) as $record)
print_r($record);
fclose($fh);
This example displays each record as an associative array with the field name as key. As you can see you can remove the second parameter of the generator function to obtain an indexed array. Feel free to choose the most convenient way to insert records into your database (one by one, by blocks, or all in one shot).
Try the PHP function file(), which gets a file as an array -- each line is an element in the array. Then you can loop through the lines starting and ending wherever you need to.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have this little piece of code I'm just testing out that basically redirects a user if their IP doesn't match the predefined IP and if it doesn't match write that IP into a text file.
$file = fopen("ips.txt", "w");
if ($ip == "iphere") {
echo "Welcome";
fclose($file);
} else {
header('Location: http://www.google.com');
fwrite($file, "\n" . $ip);
if ($file) {
$array = explode("\n", fread($file, filesize("ips.txt")));
}
$result = print_r($array, TRUE);
fclose($file);
}
What I want to do is take the IPs that I'm writing to the text file, put them all into an array to find the duplicates, make note of the duplicates, filter them out, then write them back into that file or another txt file, but I'm stuck and not sure where to go from here.
I could suggest you use serialize or json_encode to store the ip's in a file , that way you could add more info (how many times an IP has visited, last visit, etc.).
I'll show you a simple example.
1: Create some dummy ips for test.
$IPs = array(
'192.168.0.1' => array(
'visits' => 23,
'last' => '2015-07-20'
),
'192.168.0.2' => array(
'visits' => 32,
'last' => '2015-06-23'
)
);
So here we created an associative array with 2 IP addreses, that also contain visit count and last visit.
Save the file using php serialize function or json_encode (i prefer json format, because it can be used by other languages).
$for_save = json_encode($IPs); // OR serialize($IPs)
file_put_contents("FILE_NAME",$for_save); //Save the file with the IP's
Now its time to read the file
$file = fopen("FILE_NAME", "w");
$file = json_decode($file) // or unserialize($file);
and now we have the array to use as we wish and we can search for ip's using php array functions, and offcourse modify information about ips :
if(array_key_exists("YOUR_IP_HERE",$file)){
//What to do if we have found the ip in the file, for example :
$file['YOUR_IP']['visits']++; //we add +1 visit for that ip
}
And now we can save the file again
$file = json_encode($file);
file_put_contents("IP_FILE_NAME",$file);
There are a couple issues with this approach, around threading and performance. What happens if two people hit the webpage and write to the same file at the same time? Also, this file can grow to an unbounded size? This will be slow. You don't need to manually check all ip's, only that one exists.
It might be better to use a database table for this. Otherwise, you'll need to handle filelocking as well.
psuedo code for function check_ips:
Select * from ips where ip =?. Check the user id
if no result, insert the ip. it's unknown. (also if needed you can add constraint to the table to prevent duplicate ip's)
otherwise, the ip is known
You can log counts, dates, last access, or other stats in the table as a calculated summary.
You can do easly reading the file with the ip in an array and the get the unique value from the array like this
$ipList = file(ips.txt);
$ipUnique = array_unique($ipList);
then yo can save or parse the $ipUnique for your porpose.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to work on a project involving huge amount of data stored in a raw text file. Each field is delimited by its size, ie, field 1 is from position 0 to 3, etc.. (not CSV file)
The file contains over a million lines.
I need to store it into a database. I checked several posts about what would be the best way to go about it, and it seems like the technology choice matters less than the algorithm. I'm open to Php, Perl or Python. Feel free to suggest anything.
Now, the file structure in itself is a bit tricky. Here is an example:
A880780093vvd47aa8db20d4133e6f587cf046054e8316000212093659D11001
C880780093d47aa8db20d4133e6f587cf046054e831600021209365907000 0711012012C
A880780093vvcaacb22bfb091127f9c9e14175d858ee25000212093681O11001
C880780093caacb22bfb091127f9c9e14175d858ee2500021209368107000 0611012012ADI
D880780093caacb22bfb091127f9c9e14175d858ee250002120936810700011012012HK00210Z
A880780093vvb92f937a3fd1268c1478deb174a1bfca86000212093750S11041
C880780093b92f937a3fd1268c1478deb174a1bfca8600021209375007000 3911012012PB
C880780093b92f937a3fd1268c1478deb174a1bfca8600021209375007000 3911012012B 1002
E880780093212093750b92f937a3fd1268c1478deb174a1bfca8600007000110120120100000127000000000000
C880780093b92f937a3fd1268c1478deb174a1bfca8600021209375007000 3911012012B
Basically, there are 6 types of lines, from A to F; line A is the header of the block. Lines B and C have the exact same length and fields. Line D is a possible complement to line C, meaning that it is attached to a line C but not required; also meaning there cannot be a line D without a line C. Lines E and F are independent lines, only attached to line A. (all lines are part of a block, so they could all be "attached" to a line A, or a virtual block ID)
How would I go about to create a model that would allow me to:
- modify some data on some lines based on some criteria (ie, if 5th char of line C is 4, then 10th becomes 7)
- keep track of the modified ones (ie, I want to be able to link them to their original selves)
- Be able to rebuild the original text file, deleting the original lines and replacing them by their modified version
- Be able to insert new lines in the block: if line C has 7th char = 0 then I add below it a D line.
- keep the line order intact. (if one line is inserted, it moves the order for the following line by 1 rank ahead)
I thought about using a parent_id foreign key in all 5 line tables (one per each line type, since they do not have the same fields); thus resolving the line ordering issue, but I am stuck at rebuilding the modified file version. I also thought about dividing the file into blocks (starting by a line A), then linking lines to block ID...
Any suggestion would be greatly appreciated!
Thanks a lot in advance!
Go through the file line by line and use a stack. Something along the lines:
<?php
// You'd have to implement the database yourself!
$db = new Database();
$db->startTransaction();
$stack = array();
$fh = fopen("my-file", "r");
$i = 0;
while (($buffer = fgets($handle, 4096)) !== false) {
if (!isset($buffer[0])) {
continue;
}
switch ($buffer[0]) {
case "A":
// Do something ...
break;
case "C":
// Do something ...
break;
case "C":
if ($stack[$i] != "C") {
trigger_error("Line D without preceding line C");
}
// Do something ...
break;
// More stuff ...
}
$stack[$i++] = $buffer;
$db->insert("INSERT INTO table (line) VALUES ($buffer)");
}
$db->commitTransaction();
?>
Of course there are better solutions than the ugly switch, but it's quick'n'dirty. Your database design answer is impossible to answer because we have no clue about the requirements. All in all consider posting your work and ask specific questions regarding a small piece of a big problem and not asking to solve big problems.
I have a php file that writes to a txt file:
<?php
$answers = "answers.txt";
$fh = fopen($answers, 'a+') or die("can't open file");
$stringData = $_POST["username"];
$timestamp = date("g:i A, m/j/Y");
fwrite($fh, $stringData);
fwrite($fh, " started the quiz at ");
fwrite($fh, $timestamp);
fwrite($fh, "\n");
fclose($fh);
?>
Assuming I replace this code to enter a number (e.g. 10) followed by the user's answer (a string) so it submits the question number followed by the answer, how can I search through the txt file for the username then add that line to an array? Also, could I check the file when each question loads to see which questions the user has answered and then either choose another random quiz or continue loading (if they have not)?
Basically:
Search the text file for a string and output any lines that contain it
Search the text file for a string and then search for a number encased in commas or some other identifier (e.g. ,23,) on the same line as the string.
If I should be doing this using MySQL, a few links or other resources would be nice, because I have heard of MySQL but never used it.
Thanks a bunch in advance!
NOTE: I believe I need to search for a string using strpos and then get the line number and take the whole line and put it in the string. Then, I need to use explode "," to get the question numbers and have a php script on each page check to see if it's number has already been answered. If so, then select another random number. If not, recieve input then write it back to the text file. Or, perhaps I could use sessions to store the questions answered. However, I have no idea how to implement all this together.
I would say MySQL would be the better route to take.
Get Started Here: http://www.w3schools.com
Also check out other posts here:
MySql database design for a quiz
Am doing online Quiz type of script in PHP. It is better to use cookies or sessions
EDIT:
Don't forget about security!