【问题标题】:Include and ob_get_clean not working properly包括和 ob_get_clean 不能正常工作
【发布时间】:2013-09-12 09:08:48
【问题描述】:

我有三个php文件:engine.php、links.php和test.php

理论上,当我在 test.php 中调用 _insert() 函数时,它应该用 links.php 的输出替换一个字符串,而不是 ob_start()ob_get_clean() 被忽略,而 links.php 的输出只是回显.

engine.php

function db() {
    require("config.php");
    $conn = @mysql_connect($host, $uname, $pass) or die("DB error: ".mysql_error());
    @mysql_select_db($db) or die("DB error: ".mysql_error());
    @mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'"); #UTF-8 FIX
}

function _include($x) {
    if (preg_match("/<!--Include:(.*)-->/", $x, $matches)){

        ob_start();
        include($matches[1]);
        $output = ob_get_clean();

        return preg_replace("/<!--Include:(.*)-->/", $output, $x);
    }

}

links.php

<?php
$query = @mysql_query("SELECT title, description, url FROM links ORDER BY id") or die("DB error: ".mysql_error());

while($row = @mysql_fetch_array($query)) {
    $url = $row["url"];
    $title = $row["title"]; 
    $description = $row["description"];
    echo "<a href=\"$url\">$title</a>: $description";
}

@mysql_close($conn) or die(mysql_error());
?>

test.php

<?php

require("engine.php");

db();

echo _include("<div><!--Include:links.php--></div>");

?>

它不是在 div 中输出一系列链接,而是跳过 links.php 的返回完全结束回显,就好像只有一个包含而没有 ob_start()ob_get_clean()

为什么?

【问题讨论】:

标签: php include echo ob-start


【解决方案1】:

你可以从 links.php 中返回一个字符串:

<?php
$query = @mysql_query("SELECT title, description, url FROM links ORDER BY id") or die("DB error: ".mysql_error());

$links =''; //

while($row = @mysql_fetch_array($query)) {
    $url = $row["url"];
    $title = $row["title"]; 
    $description = $row["description"];
    $links .= "<a href=\"$url\">$title</a>: $description";//
}

@mysql_close($conn) or die(mysql_error());
return $links;//

然后,在 engine.php 中:

function _include($x) {
    if (preg_match("/<!--Include:(.*)-->/", $x, $matches)){

        //ob_start();
        $output = include($matches[1]);
        //$output = ob_get_clean();

        return preg_replace("/<!--Include:(.*)-->/", $output, $x);
    }

}

【讨论】:

  • 它不能回答你的问题,但它应该能解决你的问题! :)
猜你喜欢
  • 1970-01-01
  • 2017-08-11
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 2012-07-11
  • 2012-09-24
相关资源
最近更新 更多