My PHP code is generating 495 HTML pages from 495 txt files and working correctly. But right now, I'm trying to change it as a way to change the value of title tag dynamically; so I'm trying to replace %TITLE% with $Oneline that is the first line of each txt pages.
I have tried many syntaxes such as prg_replace, str_replace and much more all seems unsuccessful. In fact those lines of codes change nothing on my HTML pages.
To be more clear:
Trying to replace %TITLE% with $Oneline.
$Oneline is the first line of the txt file.
Thanks for any help.
<?php
for ($i = 1; $i <= 495; $i++)
{$j = 1;
$SousrceFile = #fopen($SousrceFile, 'r') ;
$TargetFile = fopen($TargetFile, 'w+') ;
fwrite($TargetFile, "<title>%TITLE%</title>\n");
while ($Oneline = #fgets($SousrceFile, 4096))
{$j = $j + 1;
if (strlen($Oneline) !==0)
{
$title = $Oneline;
$newTitle = preg_replace('%TITLE%', $title, $newTitle,1 );
...?>
Please take a look at preg_replace(), the parameters are
preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
In your code you are using the variable $title to replace the pattern in $newTitle with a limit of one. I think you want to replace the text in the target file instead.
Update:
There are two solutions that come into my mind right now:
Instead of writing your text into the file directly, write it into
a variable instead. This variable can be searched by
preg_replace() and you can change your title dynamically. After
you done that, write the variable into the targe file by e.g.
fputs().
Instead of replacing the title, set the title directly where it is needed, when you are writing the header section. Than there is no need for replacing.
I would recommend solution one. You know how to do that?
As far as I can see, $newTitle is not defined prior to pre_replace.
After I couldn't solve the problem, I moved the retreiving data loop to above of the title and as Aaron suggested at this post It made it quiet simple as bellow:
<?php
for ($i = 1; $i <= 495; $i++)
{$j = 1;
$SousrceFile = #fopen($SousrceFile, 'r');
$TargetFile = fopen($TargetFile, 'w+');
while ($Oneline = #fgets($SousrceFile, 4096))
{$j = $j + 1;
if (strlen($Oneline) !==0)
$title = $Oneline;
fwrite($TargetFile, "<title>{$title}</title>\n");
...?>
Related
I'm trying to count the vowels in a lengthy text, provided by a .txt file. I can successfully open the file and echo it out into the browser. What I can't seem to do is get my script to do the actual vowel counting and I'm not entirely sure why. I'm supposed to output the vowel count to a file that doesn't previously exist, but is referred to as "file_output1.txt". I'm not sure if this is what is causing the issue, or if I'm not properly accessing the text file (Assignment Input) to enable the count to occur, or if I made a syntax error my eyes just can't seem to catch right now.
This is what I've done so far, but I'm not getting the count to fill. There are hundreds of vowels in the text file and it keeps spitting out: "There are (0) vowels". I have counted letters in a string before, but I am having trouble doing it with the file. Any advice?
<?php
#openfile
$file = "Assignment2inputfile.txt" ;
$document = fopen($file,r);
echo fread($document,filesize("Assignment2inputfile.txt"));
?>
<html>
<br><br>
</html>
<?php
#vowelcount
$vowels = array("a", "e", "i", "o", "u");
$length = strlen($_POST["file_output1.txt"]);
$count = 0;
for ($i =0; $i = $length; $i++)
{
if (array_search($_POST["file_output1.txt"][$i], $vowels))
{
$count++;
}
}
echo 'There are (' . $count . ') vowels ' . $_POST["file_output1.txt"] .'.';
fclose($document);
?>
I have counted letters before, but this time it is not a short string input. How can I do this for vowels, but with a FILE instead of a string?
You could use a regex to do this quite simply
$text='The quick brown fox jumped over the lazy dog';
$pttn='#[aeiouAEIOU]#';
preg_match_all( $pttn, $text, $matches );
printf( '<pre>%s</pre>',print_r( $matches, true ) );
printf('There are %d vowels',count($matches[0]));
The array_search is meant for finding a key of a value inside an array. But, you want to count the number of vowels in a string.
Since you have already read the entire file into memory, one simple approach here would be to just strip all vowels, and then compare the length of the resulting string against the original length:
$text = $_POST["file_output1.txt"];
$length = strlen($text);
$new_text = preg_replace("/[aeiou]/i", "", $text);
echo "Number of vowels: " . ($length - strlen($new_text));
Here is a brief demo showing that the above logic is working:
Demo
Here, I have updated code.
<?php
$file = "Assignment2inputfile.txt";
$document = fopen($file, 'r');
$output = fread($document, filesize("Assignment2inputfile.txt"));
$vowels = array(
"a",
"e",
"i",
"o",
"u"
);
$length = strlen($output);
$count = 0;
for ($i = 0; $i < $length; $i++) {
if (array_search($output[$i], $vowels)) {
$count++;
}
}
echo 'There are (' . $count . ') vowels ' . $count . '.';
fclose($document);
?>
I don't quite understand, are you trying to echo the file then read it via $_POST ???. That wouldn't work. If you're using a single php file then try
$file = "Assignment2inputfile.txt" ;
$document = fopen($file,r);
$str = fread($document,filesize("Assignment2inputfile.txt"));
Now you can use $str as
$vowels = array("a", "e", "i", "o", "u");
$length = strlen($str);
$count = 0;
for ($i =0; $i = $length; $i++)
{
if (array_search($str[$i], $vowels))
{
$count++;
}
}
finally write it to required file.
P.S I haven't completely understood your question but this should help if you're trying a normal read from a local file.
Based on this:
I'm trying to count the vowels in a lengthy text, provided by a .txt
file[...] I have counted letters in a string before, but I am having
trouble doing it with the file. Any advice?
You can use the following line of code to count only vowels in a file
str_ireplace(['a','e','u','i','o'],' ',file_get_contents('Assignment2inputfile.txt'),$count);
We basically simulate an insensitive case replacement while keeping track of the number of replacements which give exactly what you need the number of vowels
Then based on this:
I'm supposed to output the vowel count to a file that doesn't
previously exist, but is referred to as "file_output1.txt".
file_put_contents("file_output1.txt",sprintf('There are %d vowels ',$count));
we use this line of code to create a new file if not exists and put a formatted string with the number of vowels as expected.
First possibility that you are sending $_POST['file_output1.txt'] from another file to here displayed file.
if you are not getting any POST data or All you have is here displayed sample file, then my friend you are wrong, you have to take form and form fields like text-field, textarea etc,
and you have to submit it at here displayed file with post request so you can take $_POST variable, i am assuming that you are doing right then your code is fine except it has 2 errors like below:
Notice: Use of undefined constant r - assumed 'r' in C:\xampp\htdocs\stackplay\count_vowels.php on line 4
You have used (file operation mode) r in fopen($file,'r') function without quote , it should be in single or double quote
see the syntax here fopen (string $filename , string $mode)
second error is logical error in for loop You have written for ($i =0; $i = $length; $i++) so it will assign length of file content to $i in first iteration and loop runs infinitely still occur execution time out or allocated memory exhausts, so to solve it replace it with for ($i =0; $i < $length; $i++)
Second Possibility that you are not getting any POST data or All you have is file displayed in sample code in question, then i am giving you solution as below:
Assignment2inputfile.txt File:
The quick brown fox jumped over the lazy dog
count_vowels.php File:
<?php
#openfile
$file = "Assignment2inputfile.txt" ;
$document = fopen($file,'r');
$text = fread($document,filesize("Assignment2inputfile.txt"));
fclose($document);
?>
<html>
<br><br>
</html>
<?php
#vowelcount
$vowels = array("a", "e", "i", "o", "u");
$length = strlen($text);
$count = 0;
for ($i =0; $i < $length; $i++)
{
if (array_search($text[$i], $vowels))
{
$count++;
}
}
echo 'There are (' . $count . ') vowels in : ' . $text .'.';
?>
//Output:
//There are (11) vowels in : The quick brown fox jumped over the lazy dog.
There can be lots of solution to count vowels from text file but i am only showing how to do it rightly, please comment if anywhere i am wrong, thanks.
I have a .lst(playlist) file with around 1800 lines of data. Each line contains a URL to an audio file that is being played on my radio station.
The thing is I need to add URLs to some Advertisements after every 'n' number of lines in that file.
There are 10 URLs of advertisements from which 1 URL needs to be added after every 5 lines.
Example: URLs of Advertisements are in this format: file1.mp3, file2.mp3 ... file10.mp3
They will be added like this: file1.mp3 on line 5, file2.mp3 on line 10, file3.mp3 on line 15 and so on. After file10.mp3 has been inserted, it will again start from file1.mp3. I hope you understand.
So far I have managed to cook up the following code, but it only takes up one string to be added and have to manually tell the line number on which the string will be added. Unable to figure out the looping logic to do the aforementioned work.
$url = "/home/station/content/file1.mp3";
$line_number = 5; //add above URL on line number 5
$contents = file('playlist.lst', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if($line_number > sizeof($contents)) {
$line_number = sizeof($contents) + 1;
}
array_splice($contents, $line_number-1, 0, array($url));
$contents = implode("\n", $contents);
file_put_contents('playlist.lst', $contents);
How can I achieve this ?
You can use array_chunk to split your array into $line_number. Then, use array_map() to add your advertisements to each group. Finally, you could reduce to a linear array. You can format the $url using sprintf().
$url = "/home/station/content/file%d.mp3"; // use %d to use using sprintf()
$line_number = 5; //add above URL on line number 5
$counter = 1;
$contents = file('playlist.lst', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// split in group of $line_number
$groups = array_chunk($contents, $line_number);
// for each group:
$groups = array_map(function($arr) use ($url, &$counter) { // pass $counter as reference
// format the link
$adv = sprintf($url, $counter++) ;
// restart to 1 if greater than 10
if ($counter > 10) $counter = 1;
// append to group
$arr[] = $adv;
return $arr ;
},$groups);
// transform to linear array
$contents = array_reduce($groups, 'array_merge', array());
// save new file
file_put_contents('playlist.lst', implode("\n", $contents));
You could do it this way, with a simple loop:
//changing it to a "model" string, we are going to add the correct file number later
$url = "/home/station/content/file";
$contents = file('playlist.lst', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$count = 0;
$AddCount = 1;
//Loop until there is nothing left in our radio list
while ($count < sizeof($contents)) {
//if we have a multiple of 5, we are inserting an ad
if (($count % 5) == 0) {
// to know wich ad to add we use our AddCounter
$tmp = $url . strval($AddCount) . ".mp3";
//As suggested by Justinas, don't forget that each time you had a line you need to also increase the index for the next one using $count%5 to know how many lines you already added
array_splice($contents, $count - 1 + ($count % 5) , 0, array($tmp));
$AddCount += 1;
if ($AddCount > 10)
$AddCount = 1;
}
$count += 1;
}
$contents = implode("\n", $contents);
file_put_contents('playlist.lst', $contents);
This way, you don't even have to handle the advertisements file selection yourself as long as they are all formated like you said.
You should do a loop in such way.
$line_number = 5;
$line_count = 0;
for($i=0; $i < sizeof($contents); $i++)
{
$line_count = $line_count +1; // start with Line 1 that +1
if($line_count == $line_number)
{
// do your magic code of adding a line
$line_count = 0; // refresh counting from the beginning
}
}
You don't need to handle each line in the file one at a time.
Leave the file contents as its original string, inject placeholders with regex, then replace those placeholders with your ad array strings.
Code: (Basic Demo)
$filename = 'playlist.lst';
file_put_contents(
$filename,
vsprintf(
preg_replace(
'/(?:.+(\R)){5}\K/', // match (and forget) 5 lines, capture the newline character
'%s\1', // inject the placeholder following the the newline character
file_get_contents($filename),
count($ads) // make the exact number of needed placeholders
),
$ads // replace the placeholders with the ad strings
)
);
I want to be able to +1 to $i every page reload.
I have come across a very simple issue, that I am struggling to find a solution online.
Heres my code:
$backupNumber = fopen("$v", "r+") or die("Unable to open file!");
$i = fread($backupNumber,filesize("invoices/invoice1/backupN.txt"));
$i = intval($i);
$i = $i + 1;
echo $i;
fwrite($backupNumber,$i);
$a = "invoices/" . $invoiceN . "/backup" . $i;
fclose($backupNumber);
and in the txt file is simply the number '1' to start off with.
The issue occurs when reloading the page when I echo $i it outputs:
2 then 13 then 1214 then 12131215 then 2147483648 etc.
I want it to simple output
2 then 3 then 4 etc
You append the text file, that is why this is happening.
My advice is to use file_get_contents and file_put_contents.
$i = file_get_contents("invoices/invoice1/backupN.txt");
$i++;
Echo $i;
file_put_contents("invoices/invoice1/backupN.txt" $i);
File get and put contents always reads the whole text file.
I don't think you need to intcast the string, it should work without it.
The code can be a one liner too. It's messy but compact.
file_put_contents("invoices/invoice1/backupN.txt", file_get_contents("invoices/invoice1/backupN.txt")+1);
After reading the number from the file, the handle is positioned at its end, so while your math is sound, you're appending the new number to the file instead of overwriting it.
One approach to handle this is to reset the handle use fseek before writing:
fseek($backupNumber, 0);
fwrite($backupNumber, $i);
You are appending the file thats why this is happening. Instead of using r+ mode just use w+ mode.
r+ mode only opens a file and allow you to read and write but dont over write the content.
Where as in w+ mode always a new empty file is created.
Do something like
$backupNumber = fopen("$v", "r+") or die("Unable to open file!");
$i = fread($backupNumber,filesize("invoices/invoice1/backupN.txt"));
fclose($backupNumber);
$backupNumber = fopen("$v", "w+") or die("Unable to open file!");
$i = intval($i);
$i = $i + 1;
echo $i;
fwrite($backupNumber,$i);
$a = "invoices/" . $invoiceN . "/backup" . $i; fclose($backupNumber);
Else you can also you fseek() to point at 0th location in file and override the content in file.
Another variation on a theme perhaps...
function updatecount(){
$file='invoices/invoice1/backupN.txt';
if( !realpath( $file ) )$i=0;
$i=intval( trim( file_get_contents( $file ) ) ) + 1;
file_put_contents( $file, $i );
return $i;
}
$count=updatecount();
echo strval( $count );
I have a text file and it is called 'Store.txt'.
I would like to know how I can read from this file and then grab the first 50 lines of numbers/text
and insert them into another text file.
I have little code because I'm not exactly sure how to go about it and I've been searching online but couldn't find much I believe an if statment is the answer?
Any way I have gave it ago but sadly it hasn't worked.
Here is how I got on-
<?php
$fileToOpen = fopen('Store.txt', 'r');
$return = '';
$count = 0;
$return. = $fileToOpen. "\n";
if ($count >= 50)
break;
}
file_put_contents($return, "Store2nd.txt");
fclose($fileToOpen);
?>
Thank you in advance for any help. (:
This will copy upto the first 50 lines without reading in the complete file:
<?php
$fileToOpen = fopen('Store.txt', 'r');
$outputFile = fopen('Store2nd.txt', 'w');
$count = 0;
while (!feof($fileToOpen)) { // We'll copy the whole file ...
if ($count++ >= 50) // ... or the first 50 lines, whichever is less
break;
$line = fgets($fileToOpen);
fwrite($outputFile, $line);
}
fclose($fileToOpen);
fclose($outputFile);
?>
Please give this a try:
<?php
$lines = file('Store.txt'); // make file content an array
$result = array_slice($lines,0,50); // take the first 50 lines
file_put_contents('Store2nd.txt', implode('', $result)); // output
?>
A better way would probably be to do a foreach loop for your text.
Then add $count++ in your loop so that the $count = 0; you've set up will increase.
Right now with your code, nothing is increasing, so $count never reaches 50.
Cheers.
I'm trying to process a for loop within a for loop, and just a little wary of the syntax... Will this work? Essentially, I want to run code for every 1,000 records while the count is equal to or less than the $count... Will the syntax below work, or is there a better way?
for($x = 0; $x <= 700000; $x++) {
for($i = 0; $i <= 1000; $i++) {
//run the code
}
}
The syntax you have will work, but I don't think it's going to do exactly what you want. Right now, it's going to do the outer loop 700,001 times, and for every single one of those 700,001 times, it's going to do the inner loop.
That means, in total, the inner loop is going to run 700,001 x 1001 = about 700.7 million times.
If this isn't what you want, can you give a bit more information? I can't really work out what "I want to run code for every 1,000 records while the count is equal to or less than the $count" means. I don't see any variable named $count at all.
Well, essentially, I'm reading in a text file and inserting each of the lines into a db. I did originally try while(!feof($f)) [where $f = filename], but it keeps complaining of a broken pipe. I thought this would be another way to go
$f should be file-handle returned by fopen(), not a filename.
$file_handle = fopen($filename, 'r');
while(!feof($file_handle)) {
$line = fgets($file_handle);
$line = trim($line); // remove space chars at beginning and end
if(!$line) continue; // we don't need empty lines
mysql_query('INSERT INTO table (column) '
.'VALUES ("'.mysql_real_escape_string($line).'")');
}
Read through the documentation at php.net for fopen(), fgets(). You might also need explode() if you need to split your string.
If your file isn't big, you might want to read it into an array at once like this:
$filelines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($filelines as $line) {
do_stuff_with($line);
}
Hmm. Ok... Well, essentially, I'm reading in a text file and inserting each of the lines into a db. I did originally try while(!feof($f)) [where $f = filename], but it keeps complaining of a broken pipe. I thought this would be another way to go..
To read a text file line by line I usually:
$file = file("path to file")
foreach($file as $line){
//insert $line into db
}
Strictly answering the question, you'd want something more like this:
// $x would be 0, then 1000, then 2000, then 3000
for($x = 0; $x < 700000; $x += 1000) {
// $i would be $x through $x + 999
for($i = $x; $i < $x + 1000; $i++) {
//run the code
}
}
However, you should really consider one of the other methods for importing files to a database.