开发者

Output PHP into a Variable for JSON

开发者 https://www.devze.com 2023-03-20 00:19 出处:网络
file1.php <?php $listMenu=array(\'Menu #1\',\'Menu #2\',\'Menu #3\'); ?> <div class=\"wjNavButton\"><a><?php echo($listMenu[0]); ?></a></div>
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"?


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. Imagine include 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号