提问人:rkrathor 提问时间:11/4/2020 最后编辑:rkrathor 更新时间:11/5/2020 访问量:328
如何使用数组中的数据解析html模板?
How to parse html template with data in array?
问:
我有一个html模板,我想附加一些具有数组的动态数据。 我能够使用简单的占位符解析数据,但是当涉及到在占位符中添加数组时,我找不到任何解决方案,如何做到这一点。我发现很多这样的问题,但它们是用于简单的解析,不包括数组。
<?php
class TemplateParser {
protected $_openingTag = '{{';
protected $_closingTag = '}}';
protected $_emailValues;
protected $_templateHtml = <<<HTML
<html>
<body>
<h1>Account Details</h1>
<p>Thank you for registering on our site, your account details are as follows:<br>
First Name: {{fname}}<br>
Last Name: {{lname}} </p>
<p> Address: {{address}}</p>
<ol>
{{transaction}}
<li> {{sn2}} - {{desc}} - {{amount}}</li>
{{transaction}}
</ol>
</body>
</html>
HTML;
public function __construct($emailValues) {
$this->_emailValues = $emailValues;
}
public function output() {
$html = $this->_templateHtml;
foreach ($this->_emailValues as $key => $value) {
$html = str_replace($this->_openingTag . $key . $this->_closingTag, $value, $html);
return $html;
}
}
$templateValues = array(
'fname' => 'Rajesh',
'lname' => 'Rathor',
'address' => ' G-8/55',
'transaction'=>array(
0=>array(
"sn2"=> 1,
"desc"=> "row 1",
"amount"=> "RS.1234"
),
1=>array(
"sn2"=> 2,
"desc"=> "row 2",
"amount"=> "RS.12345"
)
)
);
$templateHtml = new TemplateParser($templateValues);
echo $templateHtml->output();
我得到了这个结果。
<html>
<body>
<h1>Account Details</h1>
<p>Thank you for registering on our site, your account details are as follows:<br>
First Name: Rajesh<br>
Last Name: Rathor </p>
<p> Address: G-8/55</p>
<ol>
Array
<li> {{this.sn2}} - {{this.desc}} - {{this.amount}}</li>
Array
</ol>
</body>
</html>
我想要这样的结果
<html>
<body>
<h1>Account Details</h1>
<p>Thank you for registering on our site, your account details are as follows:<br>
First Name: Rajesh<br>
Last Name: Rathor </p>
<p> Address: G-8/55</p>
<ol>
<li> 1 - row 1 - RS.1234</li>
<li> 2 - row 2 - RS.123</li>
</ol>
</body>
</html>
你们能帮我解决这个问题吗?
谢谢 拉杰什
答: 暂无答案
评论
{{transaction}}
key/value
this