【问题标题】:php buffering with ob_start: synchronous alternative使用 ob_start 进行 php 缓冲:同步替代
【发布时间】:2015-12-23 19:54:40
【问题描述】:

Hy 社区

我在使用 php 时遇到了一些问题,找不到解决方案。我目前正在开发一个wordpress插件,我想做的是操作一些内容。使用 php 缓冲 (ob_start) 效果很好,但给我带来了一些新的麻烦。我正在做的是以下(最小化)。

假设我的网页包含以下文本:

Hy there, my name is A B, I am living in C with my dog D

php 代码在做什么:用子函数的输出替换一组字符串。当然,这只是一个小例子。

<?php
// -----------------------------------------
// The Function loading some content from a php file
function my_function() {
    ob_start();
    require_once("some_file.php");
    $content = ob_get_contents();
    ob_end_clean();
    return($content); // Returns new content
}
// -----------------------------------------

// Content of the web page
$content = "Hy there, my name is A B, I am living in C with my dog D";

// Strings to replace (by the content returned by "my_function")
$matches = array("A","B","C","D");

// Looping over the different matches
foreach ( $matches as $match ) {

    // Calling my_function in buffer mode
    $content = str_replace($match,call_user_func("my_function"),$content);


} ?>

好吧,现在发生的情况是缓冲是按定义异步的。一旦第一个 my_function 调用完成,整个缓冲区将被清理,并且“A”不会被“A”替换,但也包含“B”应该替换的部分替换为:)。如果只有一件事要替换,那效果很好(只有一个ob_start 进程)。

是否有任何其他方法可以捕获 include 或 require 调用的输出,或者以同步方式运行 ob_*?也许会有更好的方法我还没有找到。得到提示会很棒:)。

提前致谢!也许我完全走错了路,但这就是学习的方式:)。

复活节快乐, 重做

【问题讨论】:

    标签: php synchronization ob-start


    【解决方案1】:

    因为你使用 require_once。 但是对于 require_once 文件已经包含了 ONCE! 您可以将 require 或 include 用于多个包含。 但这是不好的方式。糟糕的架构。

    【讨论】:

    • 好吧,那是我的想法——糟糕的架构。不过谢谢回复!让我有动力再次检查我为什么要做我正在做的事情,并发现 wordpress 提供了 shortcode API ...我的错,对不起,圣诞快乐!
    • 顺便说一句:我尝试的想法或多或少正是 wordpress 短代码 API 正在做的事情。但是,当注册了这样的简码后,我的手工解决方案的问题就不会再出现了,这很好:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多