save for loop result as a string in text file - php

this is my try:-
<?php
for($i=1;$i<100000;$i++)
{
echo $i.',';
}
// save the new xml file
file_put_contents('tab_id.text', $i);
echo ' Creat Text File';
?>
This works but it only saves the last loop value. I want to save all the loop's output.

try this:
<?php
$px = '';
for($i=1;$i<100000;$i++)
{
$px.=$i.',';
}
// save the new xml file
file_put_contents('tab_id.text', $px);
echo ' Creat Text File';
?>

The $i iterator variable is incremented at every loop iteration. It does not aggregate its previous values, so naturally at the end of the loop $i evaluates to the last value assigned to it, 99999 in this case.
To achieve what you seem to look for, just aggregate the different values of $i in a separate variable, so at the end of the loop this variable will be a string made of all the values of $i.
For example:
$all_values = '';
for($i=1;$i<100000;$i++) {
$all_values .= $i.',';
}
file_put_contents('tab_id.text', $all_values);

<?php
for($i=1;$i<100000;$i++)
{
$output .= $i.',';
}
// save the new xml file
file_put_contents('tab_id.text', $output);
echo ' Creat Text File';
?>

Use this
$str = "";
for($i=1;$i<100000;$i++)
{
$str.= $i.',';
}
// save the new xml file
file_put_contents('tab_id.text', $str);
echo ' Creat Text File';

You did an echo, this will not save the value anywhere.
Try this:
<?php
echo 'Start creating text file';
$result = '';
for($i=1;$i<100000;$i++)
{
$result .= $i.',';
echo 'Adding '.$i.', to result';
}
// save the new xml file
file_put_contents('tab_id.text', $result);
echo 'End creating text file';
?>

Try to use another variable like this because i every time change the value for every loop:
<?php
$k="";
for($i=1;$i<100000;$i++)
{
echo $k.=$i.',';
}
// save the new xml file
file_put_contents('tab_id.text', $k);
echo ' Creat Text File';
?>

Related

How to comment in and out php code inside a file

Using PHP how to comment in all php code inside certain php file
for example if i've the followig file
$file = 'myfile.php';
has only PHP code
<?php
$c = 'anything';
echo $c;
?>
I want using PHP to comment in (add /* just after open tag <?php and */ just before close tag ?>) to be
<?php
/*
$c = 'anything';
echo $c;
*/
?>
And also how to do the reverse bycomment out (remove /* */) to return back to
<?php
$c = 'anything';
echo $c;
?>
I've been thinking to use array_splice then doing str_replace then using implode and file_put_contents but still unable to figure out how to do this.
Update
Okay meanwhile getting some help over here, i was thinking about it and it comes to my mind this idea .... USING ARRAY!
to add block comment /* just after open tag <?php i will convert the content of that file into array
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
and then i can array push new element at position 2 with /*
and to do the reverse i will use unset($contents[1]); to unset element at postion 2 which means, /* will be gone
later on i can file_put_contents($file, $contents); to re-write the file again.
You can use PREG_REPLACE :
<?php
function uncomment($file_path) {
$current = file_get_contents($file_path);
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', '$1', $current);
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php");
?>
BEFORE :
AFTER :
I don't know why you want comment or uncomment the php code but I don't think it's a good way to do. I advice you to use variable or constant, like this :
One other way to enable or disable you code, is to use constant variable after the second time :
TOGGLE/UNTOGGLE COMMENT :
You will be able to do :
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
FIRST TIME :
SECOND TIME :
THIRD TIME :
Code :
<?php
function uncomment_header($name, $value) {
return '<?php define("' . $name . '", ' . $value . '); ?>';
}
function uncomment($file_path, $name) {
$current = file_get_contents($file_path);
$regex = '/<\\?php define\\("' . $name . '", (0|1)\\); \\?>/';
if (preg_match($regex, $current, $match)) {
$value = ($match[1] == 1) ? 0 : 1;
$current = preg_replace($regex, uncomment_header($name, $value), $current);
} else {
$header = uncomment_header($name, 1) . "\n";
$start = 'if (' . $name . '):';
$end = 'endif;';
$current = $header . $current;
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', $start . '$1' . $end, $current);
}
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php", "MYENV_DEBUG");
?>
There are two types of comments in PHP 1)single line comment 2)Multiple line comment for single comment in php we just type // or # all text to the right will be ignored by PHP interpreter. for example
<?php
echo "code in PHP!"; // This will print out Hello World!
?>
Result: code in PHP!
For multiple line comments multiple line PHP comment begins with " /* " and ends with " / " for example
<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
/* echo "My name is Noman Ali!";
echo "PHP Programmer!";
*/?>
Result: Hello World!
Like this:
#canned test data, a string and the file contents are the same
$contents = <<<'CODE'
<?php
$c = 'anything';
echo $c;
?>
CODE;
$contents = preg_replace(['/<\?php\s/','/\?\>/'], ['<?php/*', '*/?>'], $contents);
echo $contents;
Output
<?php/*
$c = 'anything';
echo $c;
*/?>
Sandbox
NOTE - this will only work if the ending tag is present. In PHP the ending tag is actually optional. This will also not work on things like short tags <? or <?= although it will catch the ending tags.
Because of these edge cases it's very hard to do with regex (or any string replacement).
Valid examples of PHP code
<?php
$c = 'anything';
echo $c;
?>
//-------- no ending tag ---------
<?php
$c = 'anything';
echo $c;
//------- short tags ---------
<? echo 'foo'; ?>
//------- short echo tags ---------
<?= $foo; ?>
etc...
Good luck if you want to try to catch them all....

Create a php file with the value of echo values

I have a piece of code like this:
$classVoHeader = 'class C'.toCamelCase($tableName,true).'Vo{';
$classVoFooter = '}';
$str ='public $table_map = array(';
$propertyStr = '';
foreach($columnInfos as $column){
$str.=$br.'\''.$column['Field'].'\' => \''.toCamelCase($column['Field']).'\',';
$propertyStr.=$br.'public $'.toCamelCase($column['Field']).';';
}
$str.=$br.');';
echo $classVoHeader.$br;
echo $str;
echo $propertyStr.$br;
echo $classVoFooter;
And I want to create a php file that have content is all of what it echoed.
Is it impossible?
Take a look at http://www.php.net/manual/en/function.ob-get-contents.php to save what is being printed into a buffer, then use http://www.php.net/manual/en/function.file-put-contents.php to save this string to a file
Strange question but, here you go:
$Result = '<?php ' . $classVoHeader.$br . $str . $propertyStr.$br . $classVoFooter . ' ?>';
$file = fopen("result.php","w");
echo fwrite($file,$Result);
fclose($file);
i dont know what your code is and it doesnt matter. With my answer you will have all the output that is produced between ob_start(); and ob_get_clean(); saved to the variable $the_output_of_code. Then just write this to a file.
<?php
ob_start();
// your code begins here
// [your piece of code here whatever]
$classVoHeader = 'class C'.toCamelCase($tableName,true).'Vo{';
$classVoFooter = '}';
$str ='public $table_map = array(';
$propertyStr = '';
foreach($columnInfos as $column){
$str.=$br.'\''.$column['Field'].'\' => \''.toCamelCase($column['Field']).'\',';
$propertyStr.=$br.'public $'.toCamelCase($column['Field']).';';
}
$str.=$br.');';
echo $classVoHeader.$br;
echo $str;
echo $propertyStr.$br;
echo $classVoFooter;
// your code ends here
$the_output_of_code = ob_get_clean();
$file = fopen("the_output.php","w");
fwrite($file,$the_output_of_code);
fclose($file);
?>

annoying array tags.. want a pretty output

What i'm trying to do is make my output usable for a spreadsheet.
I want each item in the output without array tags or not mashed together but starting with an asterisk and ending with a % sign.
<?php
$file = file_get_contents('aaa.txt'); //get file to string
$row_array = explode("\n",$file); //cut string to rows by new line
$row_array = array_count_values(array_filter($row_array));
foreach ($row_array as $key=>$counts) {
if ($counts==1)
$no_duplicates[] = $key;
}
//do what You want
echo '<pre>';
print_r($no_duplicates);
//write to file. If file don't exist. Create it
file_put_contents('no_duplicates.txt',$no_duplicates);
?>
Maybe this would give you what you want:
$str = "*" . implode("% *", $no_duplicates) . "%";
echo '<pre>';
echo $str;
echo '</pre>';

PHP foreach loop read files, create array and print file name

Could someone help me with this?
I have a folder with some files (without extention)
/module/mail/templates
With these files:
test
test2
I want to first loop and read the file names (test and test2) and print them to my html form as dropdown items. This works (the rest of the form html tags are above and under the code below, and omitted here).
But I also want to read each files content and assign the content to a var $content and place it in an array I can use later.
This is how I try to achieve this, without luck:
foreach (glob("module/mail/templates/*") as $templateName)
{
$i++;
$content = file_get_contents($templateName, r); // This is not working
echo "<p>" . $content . "</p>"; // this is not working
$tpl = str_replace('module/mail/templates/', '', $templatName);
$tplarray = array($tpl => $content); // not working
echo "<option id=\"".$i."\">". $tpl . "</option>";
print_r($tplarray);//not working
}
This code worked for me:
<?php
$tplarray = array();
$i = 0;
echo '<select>';
foreach(glob('module/mail/templates/*') as $templateName) {
$content = file_get_contents($templateName);
if ($content !== false) {
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"$i\">$tpl</option>" . PHP_EOL;
} else {
trigger_error("Cannot read $templateName");
}
$i++;
}
echo '</select>';
print_r($tplarray);
?>
Initialize the array outside of the loop. Then assign it values inside the loop. Don't try to print the array until you are outside of the loop.
The r in the call to file_get_contents is wrong. Take it out. The second argument to file_get_contents is optional and should be a boolean if it is used.
Check that file_get_contents() doesn't return FALSE which is what it returns if there is an error trying to read the file.
You have a typo where you are referring to $templatName rather than $templateName.
$tplarray = array();
foreach (glob("module/mail/templates/*") as $templateName) {
$i++;
$content = file_get_contents($templateName);
if ($content !== FALSE) {
echo "<p>" . $content . "</p>";
} else {
trigger_error("file_get_contents() failed for file $templateName");
}
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"".$i."\">". $tpl . "</option>";
}
print_r($tplarray);

Reading text file and checkboxes - PHP

Basically the code below reads in a text file and diplays it on the screen with checkboxes near each line. But now I want the user to be able to check any box and then display the selected results in a new PHP file - I thought I would have to read in the text file again and somehow refer it to the array, but I'm still stuck, so any help would be appreciated.
Thank you.
First php file
<?php
$filename = "file.txt";
$myarray = file($filename);
print "<form action='file2.php' method='post'>\n";
// get number of elements in array with count
$count = 0; // Foreach with counter is probably best here
foreach ($myarray as $line) {
$count++; // increment the counter
$par = getvalue($line);
if ($par[1] <= 200) {
// Note the [] after the input name
print "<input type='checkbox' name='test[$count]' /> ";
print $par[0]." ";
print $par[1]." ";
print $par[2]." ";
print $par[3]."<br />\n";
}
}
print "</form>";
Second php file which should display the selected results
<?php
$filename = "file.txt";
$myarray = file($filename);
?>
I think you're over complicating the problem. You can just give the checkboxes a value atribute and read the array from the second page. Start with kus print_r ($_POST) on the second page to help you see what you have to work with.
1) Think of format of your text file (could be something like "Name1-Value 1-true\nName1-Value2-false")
2) Learn this function
3) Create a file with the default options
4) Make a PHP script that opens the file, makes an array and prints the resoult - for example:
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
$handle = null; //Similar to unset($handle);
$array = explode($fileString, "\n");
echo '<form action="./script2.php">';
foreach ($array as $value) {
$value = explode($value, "-");
echo '<input type="checkbox" name="'.$value[1].'" value="'.$value[2].'" checked="';
if ($value[3]==true) {
echo 'checked" /><br />';
} else {
echo '" /><br />';
}
}
5) Make the second script that edits the file - for example:
if ($_GET == null;) {exit("He's dead, Jim!");}
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
//Do something with the string :D
$handle = fopen('./file.txt','w');
fwrite($handle,$fileString);

Categories