22

I have a function ( DoDb::printJsonDG($sql, $db, 1000, 2) ) which echos json. I have to catch it and then use str_replace() before it is send to the user. However I cannot stop it from doing echo. I don't want to change printJsonDG because it is being used in several other locations.

ilhan
  • 8,700
  • 35
  • 117
  • 201

4 Answers4

58

You can use the ob_start() and ob_get_contents() functions in PHP.

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

Will output :

string(6) "Hello "
string(11) "Hello World"
olivier
  • 1,007
  • 8
  • 14
11

You can do it by using output buffering functions.

ob_start();

/* do your echoing and what not */ 

$str = ob_get_contents();

/* perform what you need on $str with str_replace */ 

ob_end_clean();

/* echo it out after doing what you had to */

echo $str;
N.B.
  • 13,688
  • 3
  • 45
  • 55
4

Perhaps you can refactor DoDb:

class DoDb
{
    public static function getJsonDG( $some, $parameters )
    {
        /*
            original routine from printJsonDG without the print statement
        */

        return $result;
    }

    public static function printJsonDG( $some, $parameters )
    {
        print self::getJsonDG( $some, $parameters );
    }
}

That way you don't have to touch the code elsewhere in you application.

Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
1

Check out output buffering, but I'd rather change the function now that it seems it'll be used for two things. Simply returning the string would be best.

aib
  • 45,516
  • 10
  • 73
  • 79