Get value from another file with php and assign to a variable

Viewed 19

dataDisplayer.php

    <?php
    
    $color = 'green';
    $fruit = 'apple';
    
    ?>

main.php

    <php?
    //get data from dataDisplayer.txt
    $myfile = fopen("dataDisplayer.php", "r") or die("Unable to open file!");
    $data = fread($myfile,filesize("dataDisplayer.txt"));
    fclose($myfile);
    
    extract(json_decode($data, true));
    $color = $color;
    $fruit = $fruit;
    
    echo $color;
    
    echo $fruit;
    
    
    ?>

I want to read $color value and assign to variable but it is not working. I have tested

1 Answers

$data isn't JSON, it's PHP source code, so you can't use json_decode() to parse it.

Use require to execute another PHP script.

require_once('dataDisplahyer.php');
echo $color;
echo $fruit;
Related