file get contents-PHP-字符串中包含变量的file_get_contents()


file get contents - PHP - file_get_contents() with variable in string?

收到订单后,我正试图用PHPMailer将订单通过电子邮件发送给客户。我试着这样做:

        $email_page = file_get_contents("email_order_html.php?order=$order_id");

我想把这个页面的内容作为字符串,这样我就可以用PHPMailer发送它,但由于其中有变量$order_id,这个函数无法执行页面,我该如何解决这个问题?

只有在将file_get_contents与Url感知流包装器一起使用时,才能添加查询参数,例如,它适用于http://localhost/yourfile.php?foo=bar。这样做将使用指定的查询参数向localhost上的Web服务器发出HTTP Get Request。将处理该请求,并返回请求的结果。

当仅使用带有文件名的file_get_contents时,不会有任何HTTP请求。调用将直接转到您的文件系统。您的文件系统不是Web服务器。PHP将只读取文件内容。它不会执行PHP脚本,只会返回其中的文本

您应该include文件,并手动调用脚本执行的任何操作。如果脚本依赖于order参数,请在包含文件之前通过$_GET['order'] = $orderId进行设置。

当然更好的方法之一是使用输出缓冲,并简单地包含内容创建脚本。

// $order_id is certainly available in place where file_get_contents has been used...
ob_start();
require 'email_order_html.php';
$email_page = ob_get_clean();

email_template.php

<body>
<p>{foo}</p>
<p>{bar}</p>
</body>

sendmail.php

../
$mail = new PHPMailer(); 
//get the file:
$body = file_get_contents('email_template.php');
$body = eregi_replace("[']",'',$body);
//setup vars to replace
$vars = array('{foo}','{bar}');
$values = array($foor,$bar);
//replace vars
$body = str_replace($vars,$values,$body);
//add the html tot the body
$mail->MsgHTML($body);
/...

希望它能帮助到别人;(

use require("email_order_html.php");

$order_id将在您的文件

中可用

正如Gordon所说,file_get_contents()从文件系统读取文件——文本或二进制文件,也就是说,不是这些文件执行的结果。

您可以使用Curl(docs(来执行此操作,以防您想要将脚本移动到单独的服务器。目前,简单地包括文件并将参数直接传递给所需的函数是一种更敏感的方法。

$email_page = file_get_contents("email_order_html.php?order=".$order_id);

file_get_contents也可以读取url中的内容,至少在2021年可以。