Exporting PHP code from with a PHP file - php

I need to practically generate a .PHP file using a PHP script or PHP command. The file generate will contain the following code:
<?php
class TextToSpeech {
public $mp3data;
function __construct($text="") {
$text = trim($text);
if(!empty($text)) {
$text = urlencode($text);
$lang_en="http://translate.google.com/translate_tts?tl=en&q={$text}";
$lang_ro="http://translate.google.com/translate_tts?tl=ro&q={$text}";
$lang_fr="http://translate.google.com/translate_tts?tl=fr&q={$text}";
$language=$lang_en;
$this->mp3data = file_get_contents($language);
}
}
function setText($text) {
$text = trim($text);
if(!empty($text)) {
$text = urlencode($text);
$en="http://translate.google.com/translate_tts?tl=en&q={$text}";
$ro="http://translate.google.com/translate_tts?tl=ro&q={$text}";
$fr="http://translate.google.com/translate_tts?tl=fr&q={$text}";
$lang=$en;
$this->mp3data = file_get_contents($lang);
return $this->mp3data;
} else { return false; }
}
function saveToFile($filename) {
$filename = trim($filename);
if(!empty($filename)) {
return file_put_contents($filename,$this->mp3data);
} else { return false; }
}
}
?>
I want to do this because I want to have multiple choices regarding the language:
$language=$lang_en;
and
$lang=$en;

Not sure what your question is here. Generating a PHP file is no different than generating any other kind of file. Build a string of the source code you want to write, then a simple file_put_contents('filename.php', $contents); will do the trick.
Edit: Where are $en and $lang_en coming from? Also, could these not be passed as parameters to the function? Why must they be hard-coded?
$contents = '
<?php
// your PHP here
';
file_put_contents('filename.php', $contents);
You may also want to read up on heredocs for large blocks of text, but unfortunately those will replace your variables unless you escape them all with a backslash.

Related

Retaining indentation with file_get_contents

I'm fetching html code using the code below, it works without any problem, the only issue is the indented code isn't retained
for example the fetched code looks like:
<div>
data
</div
instead of
<div>
data
</div>
php:
<?php
function getFile($file)
{
if (file_exists($file)) {
$file = file_get_contents($file);
return $file;
} else {
return false;
}
}
I understand it isn't an "issue" but if it's possible to retain the correct indent code I'd like to, thank you.
Your current code does retain the indentation, if you want more indentation then this is just an example using your code. You could use spaces as shown or a tab.
Call it with $indent as the number of spaces that you want to add:
function getFile($file, $indent=false)
{
if (file_exists($file)) {
if($indent) {
$i = (str_repeat(' ', $indent);
$file = $i . implode($i, file($file));
} else {
$file = file_get_contents($file);
}
return $file;
} else {
return false;
}
}
An alternative would be to create an indent() function and then in the above just call it:
$file = indent(file_get_contents($file), 4);
It might be a content type encoding issue. file_get_contents will read the file contents using the default charset as configured in php.ini at setting default_charset, which is UTF-8 by default.
We can use mb_detect_encoding to ensure that it is the same as the default character set, if not we have the option to convert it to the detected encoding with mb_convert_encoding.
<?php
function getFile($file) {
if (file_exists($file)) {
$file = file_get_contents($file);
$detect_enc = mb_detect_encoding($file);
if ($detect_enc != ini_get('default_charset'))
$file = mb_convert_encoding($file, $detect_enc);
return $file;
} else {
return false;
}
}
nJoy!
Just a random guess: you probably have output of few spaces somewhere in your code before you output file content to the client.
To avoid that you need to clean output. You can do that inside this getFile() function:
function getFile($file)
{
if (file_exists($file)) {
$file = file_get_contents($file);
ob_clean(); // <-- clean the output if any happened before
return $file;
} else {
return false;
}
}
Or outside where you call it I guess something like:
...
ob_clean();
echo getFile($file);

PHP - function associated with str_replace only run when needed

I was using the str_replace() function to replace some contents within a text file. My code:
$txt = file_get_contents('script.txt');
function makefile() {
$file = fopen("test.txt","w");
fwrite($file,"Hello World. Testing!");
fclose($file);
return "Done!";
}
$templates = array("{{time}}", "{{PI}}", "{{make}}");
$applied = array(date("h:i:sa"), 22/7, makefile());
$str = str_replace($templates, $applied , $txt);
echo $str;
The script.txt contains:
The time is {{time}} <br>
The value of PI is {{PI}}
As you can see, it's just a simple templating system. the makefile() function is used only for testing purpose. The script.txt file has no {{make}} templates. So normally, the makefile function won't need to be called during replacement operation. But when I run the code, it creates the test.txt. Which mean makefile() runs. Is there any way to avoid this kind of unnecessary function operations? And run them only when needed?
You would need to add strpos check. strpos in php is used to find the position a substring occurs in a string, but if the substring never occurs, then it will return false. Leveraging that, we can do:
<?php
$txt = "The time is {{time}} <br>
The value of PI is {{PI}}";
function makefile() {
$file = fopen("test.txt","w");
fwrite($file,"Hello World. Testing!");
fclose($file);
return "Done!";
}
$templates = array("{{time}}", "{{PI}}", "{{make}}");
$applied = array(date("h:i:sa"), 22/7, strpos($txt,"{{make}}") ? makefile() : false);
$str = str_replace($templates, $applied , $txt);
echo $str;
?>

How to read a csv file with php code inside?

i searched Google but found nothing what fits for my problem, or i search with the wrong words.
In many threads i read, the smarty Template was the solution, but i dont wont use smarty because its to big for this little project.
My problem:
I got a CSV file, this file contents only HTML and PHP code, its a simple html template document the phpcode i use for generating dynamic imagelinks for example.
I want to read in this file (that works) but how can i handle the phpcode inside this file, because the phpcode shown up as they are. All variables i use in the CSV file still works and right.
Short Version
how to handle, print or echo phpcode in a CSV file.
thanks a lot,
and sorry for my Bad english
Formatting your comment above you have the following code:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
echo $zeile;
}
fclose($userdatei);
// so i read in the csv file and the content of csv file one line:
// src="<?php echo $bild1; ?>" ></a>
This is assuming $bild1 is defined somewhere else, but try using these functions in your while loop to parse and output your html/php:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
outputResults($zeile);
}
fclose($userdatei);
//-- $delims contains the delimiters for your $string. For example, you could use <?php and ?> instead of <?php and ?>
function parseString($string, $delims) {
$result = array();
//-- init delimiter vars
if (empty($delims)) {
$delims = array('<?php', '?>');
}
$start = $delims[0];
$end = $delims[1];
//-- where our delimiters start/end
$php_start = strpos($string, $start);
$php_end = strpos($string, $end) + strlen($end);
//-- where our php CODE starts/ends
$php_code_start = $php_start + strlen($start);
$php_code_end = strpos($string, $end);
//-- the non-php content before/after the php delimiters
$pre = substr($string, 0, $php_start);
$post = substr($string, $php_end);
$code_end = $php_code_end - $php_code_start;
$code = substr($string, $php_code_start, $code_end);
$result['pre'] = $pre;
$result['post'] = $post;
$result['code'] = $code;
return $result;
}
function outputResults($string) {
$result = parseString($string);
print $result['pre'];
eval($result['code']);
print $result['post'];
}
Having PHP code inside a CSV file that should be parsed and probably executed using eval sounds pretty dangerous to me.
If I get you right you just want to have dynamic parameters in your CSV file right? If thats the case and you don't want to implement an entire templating language ( like Mustache, Twig or Smarty ) into your application you could do a simple search and replace thing.
$string = "<img alt='{{myImageAlt}}' src='{{myImage}}' />";
$parameters = [
'myImageAlt' => 'company logo',
'myImage' => 'assets/images/logo.png'
];
foreach( $parameters as $key => $value )
{
$string = str_replace( '{{'.$key.'}}', $value, $string );
}

php fgets function stuck the server

I have function build_additional_docs which calls another function that do few actions, but first it's call to function read_all_file, which extract the file to string variable and return it.
It's worked perfect when the function create_file_node has been called from another function.
but when it's called from build_additional_docs, the client wait to server untill time out...
I think that the function fail on fgets().
Additional comment: When I call function create_file_node whith with the same files, and the different is that file name is static string, and I have no foreach loop, the code works again...
here is my code:
function build_additional_docs($dir_name, $addDocsArr){
foreach ($addDocsArr as $doc) {
if($summery != ''){
$fileName = $dir_name . '\\' . $doc;
create_file_node($fileName);
}
}
function create_file_node($fileName){ global $base_url;
try{
$text = read_all_file($fileName);
}
catch (Exception $ex){
// some message here
}
return 0;
}
function read_all_file($file_name){
$file_handle = fopen($file_name, "r");
while (!feof($file_handle)) {
$line[] = fgets($file_handle);
}
fclose($file_handle);
return implode('',$line);
}
Found the mistake!
$addDocsArr variable is return value from explode() function for split string to seperated files names. The returned array include strings of file name with spacial characters that cannot be seen...
so when i add the code:
$fileName = $dir_name . '\\' . substr($doc, 0,strlen($doc) - 1);
the code worked.

Adding included file contents to a variable

I am trying to add a the contents of an include file to a variable.
For example I have a variable called $form:
$form = 'Hello world';
$form .= include('sidebar.inc.php');
Is there another way to do this? Because the method noted above is causing me some problems...
Instead of using include(), you can use file_get_contents() to store it in a variable:
$form = file_get_contents('sidebar.inc.php');
That won't parse the PHP before storing it in your variable so another option is a solution posted here from the include manual:
$string = get_include_contents('sidebar.inc.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
ob_start();
include('sidebar.inc.php');
$var = ob_get_flush();
file_get_contents('sidebar.inc.php') does not parse php files. (your IF LOOP ELSE stuff)
$form = file_get_contents('sidebar.inc.php');

Categories