问题
Im trying to email an order with PHPMailer to the customer when this order is received. I tried doing that this way:
$email_page = file_get_contents("email_order_html.php?order=$order_id");
I want to get the contents of this page as string so I can send this with PHPMailer but this function wont execute the page because of the variable $order_id in it, how can I fix this?
回答1:
You can only add Query Params when using file_get_contents
with an Url Aware Stream Wrapper, e.g. it would work for http://localhost/yourfile.php?foo=bar
. Doing so would issue an HTTP Get Request to a webserver at localhost with the specified query params. The request would be processed and the result of the request would be returned.
When using file_get_contents
with a filename only, there wont be any HTTP Requests. The call will go directly to your file system. Your file system is not a webserver. PHP will only read the file contents. It wont execute the PHP script and will only return the text in it.
You should include the file and call whatever the script does manually. If the script depends on the order argument, set it via $_GET['order'] = $orderId
before including the file.
回答2:
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);
/...
Hope it helps someone ;)
回答3:
One of the certainly better ways to do it would be to use output buffering combined with simply including the content creating script.
// $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();
回答4:
use require("email_order_html.php");
and $order_id
will available in your file
回答5:
As Gordon said, file_get_contents()
reads files from the filesystem - text or binary files, that is, not the result of the execution of those files.
You can use Curl (docs) to do that, in case you'll want to move the script to a separate server. At the moment, simply including the file and passing the arguments directly to the function you want is a more sensitive approach.
来源:https://stackoverflow.com/questions/6710086/php-file-get-contents-with-variable-in-string