3

Ok I know the title is a bit confusing as I can't think of a good way to explain it. There is this function which I don't have access to and it looks something like this:

<?php function myFunction() {
?> '<img src="one.jpg" />';
<?php } ?>

Ok so everytime that function is called, it echo's the img tag. But what if I want to manipulate the img tag before it echos to the screen? Is it possible?

I want to assign it to a variable first, manipulate it and then I will echo it out. Something like this:

$image_src = myFunction();
$image_src = preg_replace('/s.*"/', $image_src);
echo $image_src;

Something like this possible?

2 Answers 2

13

Use output buffering:

ob_start();
myFunction();
$output = ob_get_clean();

after that, $output will contain the html that was echoed inside the function.

Sign up to request clarification or add additional context in comments.

5 Comments

also check ob_get_contents() and what happens when you give a callback argument to ob_start()
Thanks for the reply but is output buffering the only way?
@Rick Yes, since you don't have access to the function (and therefore can't change echo to return), it is the only way.
Sorry - what if the statement inside the function wasn't an echo? Then would this still work?
You could do it without output buffering, by making a little PHP script to perform the function, then calling that script from the first with exec. That would be inefficient, but it would work without output buffering.
1

I am new to php and the first thing I did was create a generic function to echo a line to html:

function html_line ( $string ) // echo line to browser
{
  echo PHP_EOL . $string . PHP_EOL;
}

Then I made functions for simple paragraphs and images that add html tags, for example:

function html_pp ( $string ) // echo paragraph to browser
{
  html_line ( '<p>' . $string . '</p>' );
}

Other functions and variables can be used to manipulate the content any way you wish before these are called:

function html_page ( $str_title, $str_content ) // simple page with title and body
{
  html_line ( '<html>' );
  html_line ( '<head>' );
  html_line ( '<title>' . $str_title . '</title>' );
  html_line ( '</head>' );
  html_line ( '<body>' );
  html_pp ( $str_content );
  html_line ( '</body>' );
  html_line ( '</html>' );
}

function html_test () // set some variables and create a test page
{
  $test_title = 'PHP Test';
  $test_msg = 'Hello World!';
  html_page ( $test_title, $test_msg );
}

I don't know if this answers your question but it is working well for me and could be a good starting point. If you decide to separate your functions out to a different file like I did just be sure to have correct include calls and the functions will have global scope from the caller.

Comments

Your Answer

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