Create a php file with the value of echo values - php

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

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

save for loop result as a string in text file

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

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

Best way to implement PHP constants in Javascript

So I am using Codeignitor and I am trying to figure out the best way to share my constants with my javascript in a neat maintainable way.
1) in the view I could echo out my variables in like my footer (yuuuck!)
2) I could parse a partial view which contains a template for javascript and inject that in my view (maybe?)
3) I could dynamically create a javascript file like myJavascript.js.php and include that in my header.
What's the best maintainable way to implement PHP into JS in a MVC framework?
To keep my variables nicely wrapped I use a JSON object - that way I won't incur in issues with encoding, slashes, having to manually update the JavaScript every variable I add...
$variables_to_view['js_variables']['var_name'] = $var_name;
then pass it to the view
php_variables = <?php echo json_encode($js_variables) ?>;
alert(php_variables.var_name);
There doesn't seem to be anything wrong about echoing your variables in the script tag. In fact, frameworks like BackboneJS are encouraging you to do so for data you need to pass to your client-side code.
You can use short tag like this:
For Example:
You want to use $abc variable in js, then you will need to write this in js
var abc = <?=$abc?>;
You can create php file .
Something like script.js.php?outfor=1;
<?php
header("Content-type:text/javascript"); //can be application/javascript.
?>
ABC = <?php echo $abc?>
CBA = <?php echo $cba?>
BAC = <?php echo $bac?> //and so on.
Some additional info .
If you use "var" in function that variable will be visible only in that function and without "var"means global.
So.
function abc()
{
var a = 1; //only in abc()
b=2; //global
}
I know that in terms of programming skills it's not the best, but finally it's what I use and it's working. To make it short: I put all my constants in a xml file and I have this little script that generates two separate files with the same content, but different syntax. I am just pasting the code with my values. If it's useful for anybody, I'll be very happy to help.
The xml is the simplest possible; value
<?php
define("GECOXML_PATH","../xml/geco.xml");
define("PHP_GECO_FN","../.includes/geco.php");
define("JS_GECO_FN","../js/geco.js");
echo "******** GECO (GEnerate COnstants files for PHP and JS) **********<br>";
echo "<br>";
echo " input xml file: ". GECOXML_PATH."<br>";
echo " output php file: ". PHP_GECO_FN."<br>";
echo " output js file: ". JS_GECO_FN."<br>";
echo "********************************************************************<br>";
$geco = (object)xmlParse(GECOXML_PATH);
echo "<br>";
echo "<br>";
echo "************ PHP GECO ************* <br>";
echo "<br>";
$PHP = gecoPHP($geco);
echo "<br>";
echo "<br>";
echo "************** JS GECO ************<br>";
echo "<br>";
$JS = gecoJS($geco);
writeFiles($PHP, $JS);
//****** Functions *********
function xmlParse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
return simplexml_load_string($fileContents);
}
function writeFiles($PHPcontent, $JScontent)
{
echo "<br> PhP ok:". file_put_contents(PHP_GECO_FN, $PHPcontent) . "<br>";
echo "<br> JS ok:" . file_put_contents(JS_GECO_FN, $JScontent) . "<br>";
}
function gecoPHP($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "define(\"" . $key . "\",". intval($value) . ");\n";
}
else
{
$line = "define(\"" . $key . "\",\"". $value . "\");\n";
}
$phpContent = $phpContent . $line;
echo $line."<br>";
}
return "<?php\n"$phpContent."?>";
}
function gecoJS($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "var " . $key . "=". $value . ";\n";
}
else
{
$line = "var " . $key . "=\"". $value . "\";\n";
}
$JSContent = $JSContent . $line;
echo $line."<br>";
}
return $JSContent;
}
?>

Categories