我已经编写了一个PHP代码,使用mpdf API将html内容转换为pdf,现在我想要包含一个php if条件到那个html内容我该怎么做? 这是我的代码:
$cart_body='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Order Placed</title>
</head>
<body>
<table width="550" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="400" align="left" valign="top">
<a style="font-size:16px">' if(somecondition){ echo "somecontent"; }
else{
echo "somecontent";
}'</a><br />
</body>
</html>';
答案 0 :(得分:2)
您可以使用.
运算符进行连接,请参阅下面的示例:
$cart_body='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Order Placed</title>
</head>
<body>
<table width="550" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="400" align="left" valign="top">
<a style="font-size:16px">';
if(somecondition){ $cart_body .= "somecontent"; }
else{
$cart_body .= "somecontent";
}
$cart_body .= '</a><br />
</body>
</html>';
答案 1 :(得分:0)
如果您有充分的理由将所有HTML存储在变量中,可以通过以下方式有条件地更改它:
$cart_body='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Order Placed</title>
</head>
<body>
<table width="550" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="400" align="left" valign="top">
<a style="font-size:16px">'.
(somecondition?"somecontent":"othercontent")
.'</a><br />
</body>
</html>';
但是,它并不漂亮。
答案 2 :(得分:0)
您可以像这样使用
<a style="font-size:16px">';
if(somecondition){ $cart_body .= "somecontent"; }
else{
$cart_body .= "somecontent";
}
$cart_body .= '</a><br />
</body>
</html>';
答案 3 :(得分:0)
我建议使用sprintf()
方法格式化/渲染模板。像这样,您可以在模板中放置多个占位符,然后以更易读的方式训练逻辑,然后在最后将值注入占位符:)
<?php
// preparing the template
$cart_body = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>New Order Placed</title>
</head>
<body>
<table width="550" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="400" align="left" valign="top">
<a style="font-size:16px">%s</a><br/>
</td>
</tr>
</table>
</body>
</html>
EOF;
// working out the logic
$basedOnThisCondition = true;
$whatYouWantToInject = ($basedOnThisCondition) ? 'Was true' : 'Was false' ;
// Injecting value to the placeholder (%s for string)
$rendered_cart_body = sprintf($cart_body, $whatYouWantToInject);
// And here is to test the result
print_r($rendered_cart_body);
P.S。
你的html模板中有一些我在上面的例子中修复过的关闭器:)