I am writing an email module for my web app that sends a html email to a user on completion of a task such as signing up. Now as the formatting of this email may change I've decided to have a template html page that is the email, with custom tags in it that need to be replaced such as %fullname%.
My function has an array in the format of array(%fullname% => 'Joe Bloggs'); with the key as the tag identifier and the value of what needs to replace it.
I've tried the following:
$fp = #fopen('email.html', 'r');
if($fp)
{
while(!feof($fp)){
$line = fgets($fp);
foreach($data as $value){
echo $value;
$repstr = str_replace(key($data), $value, $line);
}
$content .= $repstr;
}
fclose($fp);
}
Is this the best way to do this? as only 1 tag get replaced at the moment... am I on the right path or miles off??
thanks...
I think the problem is in your foreach. This should fix it:
foreach($data as $key => $value){
$repstr = str_replace($key, $value, $line);
}
Alternatively, I think this should be more effective:
$file = #file_get_contents("email.html");
if($file) {
$file = str_replace(array_keys($data), array_values($data), $file);
print $file;
}
//read the entire string
$str=implode("\n",file('somefile.txt'));
$fp=fopen('somefile.txt','w');
//replace something in the file string - this is a VERY simple example
$str=str_replace('Yankees','Cardinals',$str);
//now, TOTALLY rewrite the file
fwrite($fp,$str,strlen($str));
That looks like it should work, but I'd use "file_get_contents()" and do it in one big blast.
A slightly different approach is to use PHP's heredocs combined with string interpolation i.e.:
$email = <<<EOD
<HTML><BODY>
Hi $fullname,
You have just signed up.
</BODY></HTML>
EOD;
This avoids a separate file, and should make things beyond simple substitution easier later.
Related
Two different values are imported by html <input> tags. They should be displayed like this: value1:value2.
But they display like this instead: value1:value2:.
I know what is causing the problem but I don't know how to solve it because I'm just a beginner with PHP.
?php
$handle = fopen("text.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $value);
fwrite($handle, ":");
}
fclose($handle);
exit;
?
An option would be to store the data in an array, and glue them together with implode.
foreach($_POST as $key => $value){
$tmp[] = htmlentities($value);
}
if($fp = fopen('text.txt', 'a')){
fwrite($fp, implode(':', $tmp));
fclose($fp);
}
Another solution would be to concat all values to a variable, and strip off the unwanted symbol with trim() or substr() and then write the value of the variable to file.
Also, it might be wise to check if the file successfully opened and depending on what you do with the saved data, to avoid an XSS attack use htmlentites() if you ever plan to echo it.
In every cycle inside the foreach you add a value and the colon. One option is to add the colon before the value is added and don't add it on the first run. Like this:
<?php
$first = true;
$handle = fopen("text.txt", "a");
foreach($_POST as $variable => $value) {
if(!$first) {
fwrite($handle, ":");
$first = false;
}
fwrite($handle, $value);
fclose($handle);
?>
The implode solution from #xorifelse is also nice
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 );
}
Okay so I have a text file and inside of the text file I have these lines:
IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.
what I am wanted to do is get the 'False' part on the fifth line.
I have the basic concept but I can't seem to make it work. This is what I have tried:
<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);
echo $info[5];
?>
And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?
I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.
Thanks.
I think you're looking for the file(), which splits a file's contents into an array of the file's lines.
Try this:
$file = file('LauncherInfo.txt');
foreach ($file as $line) {
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
echo $data['MAINT'];
Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this
<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
$split=explode(' = ',$line);
$info[]=$splitline[1];
}
echo $info[5];//prints False
?>
I'm wanting to store basic data from a single form box and I've created this php code base, but it doesn't seem to be working. Can someone take a glance and see if anything stands out to why this wouldn't work.
Edit: the csv file never updates with new data
if (isset($_POST["submit"]))
{
$name = $_POST["name"];
date_default_timezone_set('America/New_York');
$date = date('Y-m-d H:i:s');
if (empty($name))
{
echo "ERROR MESSAGE";
die;
}
$cvsData ='"$name","$date"'.PHP_EOL;
$cvsData .= "\"$name\",\"$date\"".PHP_EOL;
$fp = fopen("emailAddressses.csv", "a");
if ($fp)
{
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
}
Use the nicer way in php : fputcsv
Otherwise you need to do lot of error handling to achieve in your case.
$list = array (
array('First Name', 'Last Name', 'Age'),
array('Angelina ', 'Jolie', '37'),
array('Tom', 'Cruise', '50')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
You should look into fputcsv. This will add CSV to you file and take care of fields and line ends.
fputcsv($fp,array(array($name,$date)));
You can also specify delimiters and such if you want.
This part will not behave like you expect, the variables are not evaluated when inside single quotes:
$cvsData ='"$name","$date"'.PHP_EOL;
You will need to use double quotes:
$cvsData ="\"$name\",\"$date\"".PHP_EOL;
I want to rewrite the code below to generate a string. This string I want to attach to an eamil. It should appear as a csv file.
$fh = fopen($file,'w');
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ';', '"');
}
array_walk($aData, '__outputCSV', $fh);
fclose($fh);
Any idea's?
The obvious and lazy approach would be not to rewrite it, but to simply create a temp file and call file_get_contents() on it afterwards.
This, however, would be boring, so I'm going to suggest what is arguably an over complicated approach, but it should work nicely and will be done entirely in memory:
Use this class that is provided in the PHP manual as an example of how to write a custom protocol handler, and the following example code:
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ';', '"');
}
stream_wrapper_register("var", "VariableStream");
$myCSVdata = "";
$fh = fopen('var://myCSVdata', 'w');
array_walk($aData, '__outputCSV', $fh);
fclose($fh);
echo $myCSVdata; // Ta Da!
Your best bet is to get a MIME compatible email class that can send emails with attachments. I recall using RMail or PHPMimeMail a while back, you'll have to google it.
Else, you'll need to learn how to build MIME mail yourself. But for all the trouble that it's worth i'll really recommend you to get a class that already does that for you.
EDIT:
I didn't understand your question at first, maybe you should completly reformat and change your title. Here is my suggestion:
$data = '';
foreach($aData as $aDataLine) {
foreach($aDataLine as $aDataKey => $aDataField) {
$aDataLine[$aDataKey] = '"'.str_replace('"', '\\"', $aDataField).'"';
}
$data .= implode(',', $aDataLine)."\n";
}
//$data contains your CSV
I dont think i forgot anything, it SHOULD work out of the box...