如何使用file_put_contents()作为php文件的一部分

时间:2013-12-17 14:08:02

标签: php html

我正在使用 PHP和html 来开发一种创建报告并通过电子邮件发送的简单机制。 我使用函数file_put_contents()和函数ob_get_contents()作为参数来创建我用来通过邮件发送的html文件。 我意识到如果我在不使用ob_get_contents()的情况下使用ob_start(),它只需要获取所有文件并将其放入html文件中。这对我不好,因为我只希望文件的一部分在生成的html中。为了更清楚,我的代码看起来像这样:

<html and php code I want to include in my html file>
.
.
<html and php code I don't want to include in my html file>
.
.
<html and php code I want to include in my html file>
.
.
<html and php code I don't want to include in my html file>
.
.
.

file_put_contents('report.html', ob_get_contents());
$message = file_get_contents('report.html');
mail($to, $subject, $message, $Headers);

那么我如何只选择我想要包含在report.html中的部分?

非常感谢!

2 个答案:

答案 0 :(得分:1)

您这样做不必要,您不需要外部文件来生成报告。看看这个:

<?php
$report = '';

// ...
// Code not included in your report
// ...

ob_start();
// ...
// HTML and PHP code you want in your report
// ...
$report .= ob_get_clean();

// ...
// Code not included in your report
// ...

ob_start();
// ...
// HTML and PHP code you want in your report
// ...
$report .= ob_get_clean();

// Mail it
mail($to, $subject, $report, $headers);
?>

编辑:关于OP的评论。

您需要的是ob_get_flush()而不是ob_get_clean()。两者都将缓冲区内容作为字符串返回,但第一个将其转储到脚本输出,而第二个则清空缓冲区。

答案 1 :(得分:0)

五月或五月无法帮助


我总是处理这个问题,就像我使用vanila PHP加载页面一样,带有一个片段!以下是我永远保留并使用的一个。它有两个可能的主要功能。一个是加载一个视图(html页面),另一个是获取一个html页面作为字符串,用于包含在电子邮件正文< /强>

例如:

//  will load a page into the clients browser
//    note the page location would indicate it will get the file "index.html" from "$_SERVER["DOCUMENT_ROOT"] . '/views/'"
loadView('/views/index.html');

//  or, as would be more helpful to you
$msgHTML = loadView('/views/index.html', NULL, TRUE);

TRUE 参数只是告诉函数只返回一个字符串,而不是回应客户端。

NULL 参数,您会看到要传递的数据数组。例如,假设您有一个html页面,其中包含要为数据库调用填充的表。您只需拨打电话,将回报放入数组,然后添加到页面。

$arr = array( 'key' => 'value' );
$msgHTML = loadView('/views/index.html', $arr, TRUE);

//  then in the index.html
<div><?= $key; ?></div>

这使得构建电子邮件所需的任何HTML变得非常容易。


if (!function_exists('loadView')) {
    function loadView($file, $data=NULL, $get=FALSE) {
        if (!empty($data)) extract($data);
        ob_start();
        if (is_file($file)) include($file);
        $return = ob_get_clean();
        if (!$get) echo($return);
        return $return;
    }
}

因此你可以这样做:

$htmlFirst = loadView('report.html', NULL, TRUE);
$msgFirst = 'Some message string here';
$htmlSecond = loadView('report2.html', NULL, TRUE);
$msgSecond = 'Some message string here';

$body = $htmlFirst . $msgFirst . $htmlSecond . $msgSecond;
mail($to, $subject, $body, $Headers);