【发布时间】:2015-09-08 13:55:43
【问题描述】:
我正在开发一个 PHP 类,我在其中将变量替换为 HTML 电子邮件模板文件中的数据。它通过用数据替换像“{{first_name}}”这样的字符串来工作。
通过这种方式,我可以用客户的正确数据替换名字、姓氏、电子邮件等变量。这适用于单个值,但现在我遇到了问题。
在这封电子邮件中,我展示了客户订购的产品。这是一个数组产品,其中每个产品都有自己的规格(请看下面的示例数组)。
问题: 有谁知道如何用 products 数组的循环替换 {{variable}}?
产品数组示例:
$products = array(
array(
'name' => 'Product 1',
'price' => 10.00,
'qty' => 1
),
array(
'name' => 'Product 2',
'price' => 12.55,
'qty' => 1
),
array(
'name' => 'Product 3',
'price' => 22.10,
'qty' => 3
)
);
我的班级:
class ConfirmationEmail {
protected $_openingTag = '{{';
protected $_closingTag = '}}';
protected $_emailValues;
protected $_template;
/**
* Email Template Parser Class.
* @param string $templatePath HTML template string OR File path to a Email Template file.
*/
public function __construct( $templatePath ) {
$this->_setTemplate( $templatePath );
}
/**
* Set Template File or String.
* @param string $templatePath HTML template string OR File path to a Email Template file.
*/
protected function _setTemplate( $templatePath ) {
$this->_template = file_get_contents( $templatePath );
}
/**
* Set Variable name and values one by one or at once with an array.
* @param string $varName Variable name that will be replaced in the Template.
* @param string $varValue The value for a variable/key.
*/
public function setVar( $varName, $varValue ) {
if( ! empty( $varName ) && ! empty( $varValue ) ) {
$this->_emailValues[$varName] = $varValue;
}
}
/**
* Set Variable name and values with an array.
* @param array $varArray Array of key=> values.
*/
public function setVars( array $varArray ) {
if( is_array( $varArray ) ) {
foreach( $varArray as $key => $value ) {
$this->_emailValues[$key] = $value;
}
}
}
/**
* Returns the Parsed Email Template.
* @return string HTML with any matching variables {{varName}} replaced with there values.
*/
public function output() {
$html = $this->_template;
foreach( $this->_emailValues as $key => $value ) {
if( ! empty( $value ) ) {
$html = str_replace( $this->_openingTag . $key . $this->_closingTag, $value, $html );
}
}
return $html;
}
}
实际操作:
$template_path = 'path-to-template/email-templates/confirmation.php';
$emailHtml = new ConfirmationEmail( $template_path );
$emailHtml->setVars( array(
'first_name' => 'Jack',
'last_name' => 'Daniels',
'street' => 'First street',
'number' => '22',
// Other data
));
// Outputs the HTML
echo $emailHtml->output();
Ps.如果您愿意,我可以向您展示 HTML 电子邮件模板。这是一个 html 结构,包含许多具有内联样式的表格,并且在需要替换数据的地方有 {{variables}}。
【问题讨论】:
标签: php arrays email oop replace