-2

Hy community

I have some troubles with php and could not find a solution. I am currently developing a wordpress plugin, and what I would like to do is to manipulate some content. Using php buffering (ob_start) which works fine, but gives me some new troubles. What I am doing is the following (minimalized).

Let's assume that my webpage contains the following text:

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

What the php code is doing: replace a set of strings with the output of a subfunction. Of course, this is just a minimal example.

<?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);


} ?>

Well, what happens now is that the buffering is per definition async. As soon as the first my_function call is finished, the whole buffer will be cleaned and "A" is not replaced by what "A" should be replaced, but also contains parts of what "B" should be replaced with :). If there is only one thing to replace, that works excellent (only having one ob_start process).

Is there any other way to catch output of a include or require call, or to run ob_* in a synchronous way? Maybe there would be a way nicer way I have not found. Would be great to get a hint :).

Thanks in advance! Maybe I am completely on the wrong track, but that's how things are getting learned :).

Happy easter, Reto

1 Answer 1

2

Because you use require_once. But for require_once file has included ONCE! You can use require or include for multiple including. But this is bad way. Bad architecture.

2
  • Well, that was I thought - bad architecture. But thanks for the reply! Gave me motivation to check again why I am doing what I am doing, and found out that wordpress offers a shortcode API ... my fault, sorry, and merry Christmas! Dec 24, 2015 at 7:01
  • BTW: the idea I tried is more or less exactly what the wordpress shortcode API is doing. However, when such a shortcode is registered, the problem I had with my hand-made solution does not occur anymore, which is good :). Dec 29, 2015 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.