1

I have:

 if ( isset( $_POST["test"] ) ) { 

$html1 = $object->htmlmarkup1();
$html2 = $object->htmlmarkup2();
$json = array("html1" => $html1, "html2" => $html2);

die(json_encode($json));
}

The functions echo html markup based on some calculations from the "test" POST data. The functions are using echo instead of return because I am using these functions elsewhere and the format of my code is easier to just echo the results of the functions rather than return the result first.

I have tested this without using functions by putting "test1" and "test2" in the two array elements and the resulting json decodes and displays "test1" and "test2" correctly in my test page.

1

1 Answer 1

3

You can use output buffering. This allows you to save the output in a buffer instead of sending it to the client, and then getting it back (eg to store it in a variable).

See ob_start(), ob_get_clean() and all the other associated functions.

// from now on, output is not sent to the client but saved in a buffer
ob_start(); 
$object->htmlmarkup1();
// get the content of the buffer into $html1 and turn off output buffering
$html1 = ob_get_clean(); 

ob_start();
$object->htmlmarkup2();
$html2 = ob_get_clean();

$json = array("html1" => $html1, "html2" => $html2);
Sign up to request clarification or add additional context in comments.

1 Comment

good one, it's funny how languages almost always have features which solve problems directly but you don't use them until you come across the problem yourself. I will accept this answer once the time limit.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.