CodeVolunteer
CodeVolunteer

Reputation: 143

How to output interpreted PHP-code from file_get_contents() of a PHP file?

I want to include the content of a file $source, which has php-code inside.

// using_source.php
$source = '../filepath/..';

<?php echo file_get_contents($source); ?>

source.php

<?php $multiplicator = 2; ?>
<?php echo 1 * $multiplicator; ?> Apples <br>

I get following:

Apples

I want:

2 Apples

Any approaches to solve this?

Upvotes: 1

Views: 1998

Answers (2)

Mikey
Mikey

Reputation: 2704

I think you may want to take a different approach to your problem like other people have mentioned.

I'm going to presume your two files are in the same directory, if not you may need to alter the below slightly.

source.php

<?php

// The variable we want to work with
$multiplicator = 2;

index.php

<?php 

require 'source.php';

echo (1 * $multiplicator) . ' Apples';

I'm not exactly sure on what your use case is for this to be honest, it seems a little odd but the above should at least fix your issue.

The reason why your current code is not working is due to the fact file_get_contents() returns the content as a string, that string isn't parsed by PHP so you do not have access to any variables you declared in a file that you call by file_get_contents()

Hope that helps, and here's the DOCs for file_get_contents() and require: http://php.net/manual/en/function.file-get-contents.php

http://php.net/manual/en/function.require.php

Upvotes: 1

Will
Will

Reputation: 24699

Instead of using file_get_contents(), use include():

<?php include($source); ?>

This will actually run the code through the PHP interpreter, rather than just printing its text-contents inside the page.

Upvotes: 2

Related Questions