0

I am trying to create an array that should return some html as well of some other data through an ajax call. The thing is I need to include a php file that first has to build the HTML page, bue when I use a command like file_get_contents():

$array['nav'] = array(
    1 => false
);

$array['content'] = array(
    1 => file_get_contents('filename.php')
);

$array['stylesheets'] = array(
    1 => 'admin'
);

It just returns all my php code as well in the array.. I have also tried to use include(), but it automatically displays all the HTML before I can echo a json-encoded array, which won't work with my AJAX call. Any idea how to solve this?

Ex.

file_a.php

$array['nav'] = array(
    1 => false
);

$array['content'] = array(
    1 => file_get_contents('file_b.php')
);

$array['stylesheets'] = array(
    1 => 'admin'
);

file_b.php

<div class="something">
    <?php
        foreach($data as $key => $value) {
            echo 'This is a ' . $value . '\n';
        }
    ?>
</div>

This code will make the $array['content'][1] have the value <div class="something"> <?phpforeach($data as $key => $value) { echo 'This is a ' . $value . '\n'; } ?> </div> instead of the actual HTML

1
  • Don't rly understand your problem. If you wanna get all code from a file -> do something else with ajax -> use code from the file you could just do "file_get_contents(..) -> ajax call -> eval()". But maybe I dont understand your problem Commented Jun 7, 2014 at 18:00

1 Answer 1

2

Use output buffering for the include.

ob_start();
include(file);
$content = ob_get_clean();
$array['content'] = array(
    1 => $content
);
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! This actually solved it.. wonderful.. Should probably read more about that ob stuff. Seems it can do a lot of powerful stuff.. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.