简体   繁体   中英

Requiring an html page but not echoing it

I'm working with json and AJAX in order to get some HTML without refreshing the page. The AJAX call call a function that simplified is like this:

function postHTML($post) { // returns the HTML structure for a post starting from an array of variables
    # other stuff
    require('post.template.php'); // which is mostly HTML with just few php variables embedded
}

$data = '';
foreach ($posts as $post) {
    $data .= postHTML($post);
}

After this I manage the json as follows:

echo json_encode(array('success' => true, 'data' => $data));

Where data should be the HTML structure of each post loaded. The problem is that when i require the 'post.template.php' file it uses require and it returns the data to Javascript as:

[HTML posts] {"success": true, "data": ""}

How can I get the HTML into a variable and then pass it to json_encode without actually requiring the page (that should still be executed as PHP)?

You can use Output buffering , arround your require, to capture the output, preventing it from being echoed : it'll get stored in memory, and you'll be able to fetch it to a variable.


Basically, this would mean using the following kind of code :

ob_start();

// Output is no longer sent to the standard output,
// but stored in memory
require('post.template.php');

// Fetch the content that has been stored in memory
$content = ob_get_clean();


As a couple of references :

<?php

function postHTML($post) { // returns the HTML structure for a post starting from an array of variables
    ob_start();
    # other stuff
    require('post.template.php'); // which is mostly HTML with just few php variables embedded
    $output = ob_get_contents();
    ob_end_clean();

    return $output;
}

$data = '';
foreach ($posts as $post) {
    $data .= postHTML($post);
}

Put all of the data-generating code in another function and call it when necessary. (Yes nested functions are allowed in PHP, but not sure this works in your case since you're using 'require')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM