comenk
comenk

Reputation: 69

Output PHP into a Variable for 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"?

Upvotes: 0

Views: 134

Answers (2)

deceze
deceze

Reputation: 522024

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.

Upvotes: 1

GregSchoen
GregSchoen

Reputation: 404

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.

Upvotes: 1

Related Questions