malavv
malavv

Reputation: 583

PHP include w/o echo

I'm coding a web site and I have a php fonction called site_nav.php which first define a $list array and than echos it in a json form.

This way, I can get my web site map with ajax.

My problem is that now, I would like to get the $list object in php, without echoing the json object.

My question: Is there a way to include my php file without activation of the echo call which is in it?

Thanks a lot!

Upvotes: 8

Views: 6381

Answers (5)

user105719
user105719

Reputation: 11

It's not possible without a hack. You could use output buffering:

<?php
ob_start();
echo "foo";
ob_end_clean();

Instead of the echo, you put your include statement there.

Upvotes: 1

MacAnthony
MacAnthony

Reputation: 4521

You could use an output buffer to catch the output in a string.

ob_start();

include_once('file.php');

var $output = ob_get_contents();

ob_end_clean();

Upvotes: 9

koen
koen

Reputation: 13737

You may want to look into output buffering:

https://www.php.net/manual/en/book.outcontrol.php

Though I suspect the design of your application can be improved so you don't need this.

Upvotes: 0

Byron Whitlock
Byron Whitlock

Reputation: 53871

You can use output buffering to achieve this.

ob_start();
include("myfile.php");
ob_end_clean();

Upvotes: 3

TJ L
TJ L

Reputation: 24462

Yes, just use output buffering. See the documentation on ob_start and ob_end_clean.

ob_start();
include("file.php");
ob_end_clean();

Upvotes: 21

Related Questions