How to put new line in php file fwrite - php

I am writing a file that is plan.php. It is a php file that I am writing. I am using \n to put the new line in that file but it is giving me save output.
Here is code:
$datetime = 'Monthly';
$expiry = '2017-08-07';
$expiryin = str_replace('ly', '',$datetime);
if($expiryin == 'Month' || $expiryin == 'Year') {
$time = '+ 1'.$expiryin.'s';
} else {
$time = '+'.$expiryin.'s';
}
$expiry_date = date('Y-m-d', strtotime($time, strtotime($expiry)));
$string = createConfigString($expiry_date);
$file = 'plan.php';
$handle = fopen($file, 'w') or die('Cannot open file: '.$file);
fwrite($handle, $string);
And the function is:
function createConfigString($dates){
global $globalval;
$str = '<?php \n\n';
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
$str .= '$data["'.$val.'"] = "'.$globalval[$val].'"; \n';
}
$str .= '\n';
return $str;
}
But it is giving the output like:
<?php .......something....\n.....\n
So my question is how to put the new line in this file.
Note: There is no error in code. I have minimized the code to put here.

As everyone already mentioned '\n' is just a two symbols string \n.
You either need a "\n" or php core constant PHP_EOL:
function createConfigString($dates){
global $globalval;
// change here
$str = '<?php ' . PHP_EOL . PHP_EOL;
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
// change here
$str .= '$data["'.$val.'"] = "'.$globalval[$val].'";' . PHP_EOL;
}
// change here
$str .= PHP_EOL;
return $str;
}
More info about interpreting special characters in strings http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Replace ' with " ;-)
You can learn more about strings in PHP's manual: http://docs.php.net/manual/en/language.types.string.php

If you use \n inside a single-quoted string ($var = '\n';), it will be just that - the litteral string \n, and not a newline. For PHP to interpret that it should in fact be a newline, you need to use doublequotes ($var = "\n";).
$var = '\n'; // The litteral string \n
$var = "\n"; // Newline
PHP.net on double quoted strings
Live demo

\n does not work inside single quotes such as '\n'. You need to use double quotes "\n". So for your purpose, the change you need to make is:
function createConfigString($dates){
global $globalval;
$str = '<?php \n\n';
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
$str .= "$data['".$val."'] = '".$globalval[$val]."'; \n"; // change places of double and single quotes
}
$str .= "\n"; // change places of double and single quotes
return $str;
}

Related

PHP prevent extra empty line when writing text to file

I'm having a small issue regarding a foreach() loop and writing an array to a text file within.
The loop gives me the format in the file that I want but it also adds (as I was told) an unwanted empty line at the end of the file.
Here is my piece of code:
foreach($data_arr as $data => $input)
{ fwrite($fh, $data . ":" . $input . "\n") or die("something went wrong here"); }
Is there a way to prevent this from happening and not add the \n when it reaches the end of the array?
You can do something like this :
$data_array = ['c', 'h', "hf"];
$last = count($data_array) - 1; #size of the array
foreach($data_array as $data => $input)
{
$separator = $data == $last ? "" : "\n"; #if is last, then seperator isn't a back to line
fwrite($fh, $data . ":" . $input . $separator);
}
Just check if current index is the last one, then eventually add "\n" to the string
$last_index = count($data_arr)-1;
foreach ($data_arr as $data => $input)
{
$string = $data . ":" . $input;
if ($data != $last_index)
{
$string .= "\n";
}
fwrite($fh, $string) or die("something went wrong here");
}
Determining whether you are doing something for the last time, is cumbersome - for starters, you need to count your items, and then you need a loop index to compare to that count …
Much easier to determine, whether you are doing something for the first time. So just reverse your logic here - do not try to output “all lines, followed by a newline each, except the last one”, but instead, output “all lines preceded by a newline each, except the first one.”
You could use a simple boolean flag for that:
$is_first_line = true;
foreach($data_arr as $data => $input) {
fwrite($fh, ($is_first_line ? "" : "\n") . $data . ":" . $input);
$is_first_line = false;
}
Or you just append a variable before the line data all the time - and simply make that variable “empty” on the first iteration, and then fill it with a newline character for all the following ones:
$prefix = "";
foreach($data_arr as $data => $input) {
fwrite($fh, $prefix . $data . ":" . $input);
$prefix = "\n";
}

How can echo the string in PHP to output variable “$_GET" and “[ ]"?

I have a script that read in a text file using foreach loop, but the string is unable to recognize "$_GET" or "[ ]" to display or to echo out the string. If the the echo works correctly then I can append the string output to another php file to execute, but I'm not able to make the string to echo appropriately. Please advice. Thx
<?php
$filename = "./client.txt";
echo $filename ."\n"."<br>" ;
$contents = file($filename);
foreach ($contents as $line) {
$line = str_replace(PHP_EOL, '', $line);
$str = " $$line=$_GET["$line"]; " ;
echo $str;
}
?>
--------------------------------------
Text file: client.txt
DEPLOYMENT_ID
CLINICAL_APP
ZOO_MAX
SVN_REPO
---------------------------------------
Echo output should be:
$DEPLOYMENT_ID=$_GET["DEPLOYMENT_ID"];
$CLINICAL_APP=$_GET["CLINICAL_APP"];
$ZOO_MAX=$_GET["ZOO_MAX"];
$SVN_REPO=$_GET["SVN_REPO"];
If you just want to echoing it, use ' single quote inside GET :
$str = " $$line=$_GET['" . $line . "'] " ;
you can use sprintf
like sprintf("$%s=\$_GET['%s']",$line,$line);

php eval condition understanding

I am learning PHP. I see a code including "eval" below:
<?php
$name = 'cup';
$string = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$cup = \"$str\";");
echo $cup. "\n";
?>
My question is about "\$cup = \"$str\";" . Why do I have to use \, " and ; to run the above code? Simply eval($cup = $str) gives me error.
Simply eval($cup = $str) is wrog, eval need a string, eg;
eval('$cup = $str;'); // this work
now, if use double quote, eg
eval("\$cup = \"$str\";");
in double quote strings variables in the strings will be evaluated. eg:
$cup = 'hello';
$str = 'world';
eval("$cup = \"$str\";"); // eval("hello = \"world\";");
\is a escape characters
$cup = 'hello';
$str = 'world';
eval("\$cup = \"$str\";"); // eval("$cup = \"world\";");
recommended reading: PHP Strings
Side note: PHP eval is evil (use very, very careful)

How to echo a variable that's not a variable yet

I'm struggling with the following script:
$filename = '../lang.nl.php';
$string = '<?php // language = ' . $filename . '<br>';
foreach ($_POST as $param_name => $param_val) {
$string .= "$lang=['". $param_name ."'] = ". $param_val .";\n";
}
$string .= "?>";
file_put_contents($filename, $string);
As you can see I want to create a language file with all the $_POST variables but PHP sees the $lang in $string as a variable. You can imagine that this is not what I want, it should just print $lang not whatever $lang as a variable should be. I get the error that $lang doesn't exist but I just want to literally print $lang.
Escape the $: $string .= "\$lang=['". $param_name ."'] = ". $param_val .";\n";
What is different from the original code is the backslash before $lang, which makes the $ sign an ordinary $ sign and not a marker for a variable name.
It's easier (and safer) to use var_export here:
$filename = '../lang.nl.php';
$post = var_export($_POST, true);
$code = "<?php // language = $filename;
\$lang = $post;
?>";
file_put_contents($filename, $code);
"$lang=['". $param_name ."'] = ". $param_val; is going to fail if param_val contains a quote.

How to wrap string in span before and after all newlines in PHP?

Upon searching I found PHP function that do inserts before all newlines in a string which is
nl2br();
example:
<?php
echo nl2br("This is an example\r\n where line breaks\r\n added", false);
?>
Above code Output :
This is an example<br\>
where line breaks<br\>
added
What I wanted to have output instead of <br/> I will wrap the string with the tags before and after all newlines
example output from code above wrap string with span
<span>This is an example</span>
<span>where line breaks</span>
<span>added</span>
Is there PHP function exist to this? or a custom PHP function
$str = "This is an example\r\n where line breaks\r\n added";
$str = explode("\r\n",$str);
foreach($str as $key => $value) {
echo "<span>".$value."</span>";
}
You could do an "explode" on "\r\n" and loop over each value with a concatenated span.
Something like
$values = explode("\r\n", "one\r\ntwo\r\nthree\r\nfour")
$newvalues = ""
foreach($values as $value){
$newvalues = $newvalues . "<span>" . $value . "</span>"
}
Use file(). It will return the entire file as an array, each being a new line. Iterate through there and add your span's. Not the best way, but if you have a lot of files to do this for, it's just as easy as any other solution. Otherwise, just explode on your delimiter.
function splitToSpans($string) {
$lines = explode('\r\n', $string);
$finalString = '';
foreach ($lines as $line) {
$finalString .= '<span>' . $line . '</span>';
}
return $finalString;
}
Something like:
$strout = '';
$lines = explode(PHP_EOL, $input);
foreach ($lines as $line) {
$strout .= "<span>$line</span>";
}
Option 1:
<?php
$string = "Line 1
Line 2
Line 3";
$string = preg_replace('/^(.*)$/m', '<span>$1</span>', $string);
echo $string;
Option 2:
<?php
$string = "Line 1\r\nLine 2\r\nLine 3";
$string = array_map(function($value) {
return "<span>$value</span>";
}, explode("\r\n", $string));
echo implode("\r\n", $string);
This function splits the string based on either a CRLF or LF only and then wraps it into a <span> tag, applying proper escaping (important):
function nl2span($str)
{
$r = '';
foreach (preg_split("/\r?\n/", $str) as $line) {
$r .= '<span>' . htmlspecialchars($line). '</span>';
}
return $r;
}
If your line endings are always CRLF you can replace the preg_split() with a more conventional explode("\r\n", ...).
$string = "This is an example\r\n where line breaks\r\n added";
var_dump($string);
// string(46) "This is an example
// where line breaks
// added"
array_map(function($s){echo sprintf('<span>%s</span>', trim($s));}, explode("\r\n", $string));
// <span>This is an example</span>
// <span>where line breaks</span>
// <span>added</span>
This is useful:
function nl2span( $str) {
return '<span>' . implode( '</span><span>', explode( "\r\n", $str ) ) . '</span>';
}
Read through the answers, and noone had mentioned this solution...
$string = "This is an example\r\n where line breaks\r\n added";
echo '<span>' . str_replace('\r\n', '</span><span>', $string) . '</span>';

Categories