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

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);

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....

How to put new line in php file fwrite

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;
}

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);
?>

Display white spaces that precede the content of the line of the file - PHP

I'm currently using foreach loop to display the contents of a text file. However, I want to also display the whitespaces that precede the actual content of the line. How to do so?
$loop_var = 0;
foreach($lines as $line) {
$loop_var++;
if ($loop_var == 1) {
echo'<div id="h1">' . $line . '</div>';
}
if ($loop_var == 2) {
echo '<div id="h2">' . $line . '</div><br />';
}
if ($loop_var > 2) {
if ($loop_var == 3) { echo '<pre><div id="code">'; }
echo ($line) . "<br />";
}
}
echo '</pre></div>';
Now, if the textfile contains the following:
blah
blah
blah
blah
It is getting displayed as:
blah
blah
blah
blah
Use <pre> tag, and print the content of textfile into this.
example:
print '<pre>'.file_get_contents('filename.txt').'</pre>';
Line By line (With conditions)
$file = fopen('filename','r');
print '<pre>';
$counter = 0;
while( $line = fgets($file) ){
if( /*the condition comes here whitch line you want to print. example: */ $counter >= 2 ){
print $line;
}
if( /*the condition comes here where wants you end the printing. example: */ $counter >= 10 )
$counter++;
}
print '</pre>';
fclose($file);
When you read text from a file and output that text again, the whitespace is still there.
But: if you are outputting HTML, and viewing the output in a browser, the whitespace is ignored. That's just the normal way html is displayed by a browser.
Use your browser to view the HTML source code (e.g. CTRL-U in firefox) to check if this is the case.
If you want the whitespace to be displayed in your webpage you can use the pre-Tag, or use the CSS property "whitespace" http://www.w3schools.com/cssref/pr_text_white-space.asp.
<pre><?php echo $file_content ?></pre>
or
<p style="whitespace:pre;"><?php echo $file_content ?></p>
See demo here: http://jsfiddle.net/bjelline/CjXMe/
Well, you can brute-force it if you wish ... only in case you're really stuck!
1) Get the length of the string with strlen()
2) Run a loop on the characters in the string and check for a space with strpos
3) Concatenate an html space to an empty string and print before-hand
$str = " whatever is in here ... ";
$spaces = "";
for( $i=0; $i<strlen($str); $i++ ){
if( strpos( $str, ' ', $i ) ){
$spaces .= " ";
}
}

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>';

Categories