Laz  Karimov
Laz Karimov

Reputation: 714

Execute PHP code into variable

Is it possible to execute PHP code into variable? For example I have index.php and page.php files in the same directory. If you execute page.php you will have a part of HTML page. I want to put this as a string into a variable in index.php. Any suggestions?

Upvotes: 0

Views: 3003

Answers (6)

Asad Saeeduddin
Asad Saeeduddin

Reputation: 46628

You could use cURL to retrieve the output of the script and save it to a variable. Here's what you would do in index.php:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘page.php’);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$contents = curl_exec ($ch);

Please note that it is unnecessary to include the other script (and the associated variables) into your page when all you want is the response. Including the script means you have to avoid conflicts between variable names, function names etc.

Upvotes: 0

SimSimY
SimSimY

Reputation: 3686

You didn't geve an example code so I'll assume that the page actually prints (using echo, print and etc) and then you can use php output buffering.

<?php


ob_start();

require_once('index.php');

$out = ob_get_contents();

ob_end_clean();

?>

(edit)

This is a solution but its defiantly not the best practice... that would be to but the move the code that prints the HTML into functions that generate the HTML and return it, then move those functions into a separate file that would be included in both index.php and page.php and then simply call the functions. Including a file that should print some output, and warping it with output buffer makes the code unreadable and messy.

Upvotes: -1

Benjamin Paap
Benjamin Paap

Reputation: 2759

You should try this:

ob_start()
include('page.php');
$variable = ob_get_clean();

This starts an output buffer, includes the page.php file and writes everything that was written to the output buffer to $variable

Upvotes: -2

johannes
johannes

Reputation: 15969

You can use the output buffer:

<?php
ob_start();
include('page.php');
$page = ob_get_clean();
?>

Mind that page.php is still executed in the same context (global variables, functions etc. continue to exist)

In general doing something like that sounds like broken design and page.php should be rewritten properly.

Upvotes: 5

Lasse Andersen
Lasse Andersen

Reputation: 85

If you want to execute some of you code from page.php, you can include the file and make a function in page.php like this:

<?php include('page.php');
   $test = function MyHtmlCode();
   echo $text;
?>

Upvotes: 0

Paul Dessert
Paul Dessert

Reputation: 6389

include('page.php');

This will include everything from page.php into index.php

Upvotes: 2

Related Questions