将PHP输出为JSON的变量
问题描述:
file1.php
<?php
$listMenu=array('Menu #1','Menu #2','Menu #3');
?>
<div class="wjNavButton"><a><?php echo($listMenu[0]); ?></a></div>
<div class="wjNavButton"><a><?php echo($listMenu[1]); ?></a></div>
<div class="wjNavButton"><a><?php echo($listMenu[2]); ?></a></div>
file2.php
$buff=include('file1.php');
$rest='[{sectionId:"LT", sectionType:"menu", sectionData="'.$buff.'"}]';
echo($rest);
result:
[{sectionId:"LT", sectionType:"menu", sectionData="1"}]
question:
- is this possible to put result of php page in variable?
- how i can result as output of file1.php and not sectionData="1"?
file1.php
&lt;?php
$ listMenu = array('Menu#1', '菜单#2','菜单#3');
?&gt;
&lt; div class =“wjNavButton”&gt;&lt; a&gt;&lt;?php echo($ listMenu [0]); ?&gt;&lt; / a&gt;&lt; / div&gt;
&lt; div class =“wjNavButton”&gt;&lt; a&gt;&lt;?php echo($ listMenu [1]); ?&gt;&lt; / a&gt;&lt; / div&gt;
&lt; div class =“wjNavButton”&gt;&lt; a&gt;&lt;?php echo($ listMenu [2]); ?&gt;&lt; / a&gt;&lt; / div&gt;
file2.php
$ buff = include('file1.php');
$ rest ='[{sectionId:“LT”,sectionType :“menu”,sectionData =“'。$ buff。'”}]';
echo($ rest);
结果:
[{sectionId:“LT”,sectionType:“menu”,sectionData =“ 1“}]
问题:
-这可以将php页面的结果放在变量中吗?
-我怎么能得到file1.php的输出而不是sectionData =”1“?
code > pre>
div>
答
ob_start();
include 'file1.php';
$buff = ob_get_clean();
$data = array(array('sectionId' => 'LT', 'sectionType' => 'menu', 'sectionData' => $buff));
echo json_encode($data);
- You can't get the contents of a page using
$buff = include
. Imagineinclude
as copy and pasting the contents of one file into another. It doesn't return anything. (Unless you structure your include files differently so it does, read the documentation.) - You can capture and get the content using output buffering though.
- Never write your own JSON, use
json_encode
to make sure your syntax is correct and values are escaped properly.
答
file2.php
$buff=include('file1.php');
$rest='[{sectionId:"LT", sectionType:"menu", sectionData="'.$buff.'"}]';
echo($rest);
Looks like you needed a closing quote on that string.