Search code examples
phpechorequire

Load require file and do not show the lines displayed(echo) in file


I have a PHP file that echo (displays) a array. I cannot clone this file. Now I want to use this array in another script, so I require_once it. Though now it also echo (displays) the array which i don't want.

Is there a way to load in the array but not echo the data?


Solution

  • You can use ob_start() and ob_end_clean() to block whole output of 'required' script. In example code below first.php 'requires' second.php, and in second.php is declared and printed an array $array.

    Since all output of second.php is being captured into memory buffer, after executing first.php $array will be printed only once in the output.

    first.php

    <?php
    ob_start();
    require_once 'second.php';
    ob_end_clean();
    print_r($array);
    ?>
    


    second.php

    <?php
    $array = array( 'a', 'b', 'c');
    print_r($array);
    ?>