如何存储JSON编码的结果数组的函数?

时间:2022-10-07 21:28:14

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.

这些函数基于“测试”后数据的一些计算来响应html标记。函数使用echo而不是return,因为我在其他地方使用这些函数,而且我的代码的格式更容易只返回函数的结果,而不是首先返回结果。

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.

我已经在两个数组元素中放入“test1”和“test2”,并在测试页面中正确地显示“test1”和“test2”,而没有使用函数进行测试。

1 个解决方案

#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.

参见ob_start()、ob_get_clean()和所有其他相关函数。

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

#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.

参见ob_start()、ob_get_clean()和所有其他相关函数。

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