September 4, 2012

Echo an array from another PHP file

Question by Curtis

I’m currently stuck on what I thought would be an easy solution… I’m working with PHPFileNavigator, and the only thing I’m stuck on is how I can echo the Title that is returned to an array on a separate file. Every time a file is created/edited for an uploaded file, it generates the following file below when a title is added to the file.

Update

Generally all I’m wanting to do is return the one Array value from my destination file which in this case would be from the ‘titulo’ key, and then print it back to my source file.

Destination File

 <?php
 defined('OK') or die();
 return array(
    'titulo' => 'Annual 2011 Report',
    'usuario' => 'admin'
 );
 ?>

Source File

<?php
  $filepath="where_my_destination_file_sits";
  define('OK', True); $c = include_once($filepath); print_r($c);
?>

Current Result

Array ( [titulo] => Annual 2011 Report [usuario] => admin )

Proposed Result

Annual 2011 Report

All I’m wanting to find out is how can I echo this array into a variable on another PHP page? Thanks in advance.

Answer by Starx

If you know the file name and file path, you can easily capture the returned construct of the php file, to a file.

Here is an example:

$filepath = 'path/to/phpfile.php';
$array = include($filepath); //This will capture the array
var_dump($array);

Another example of include and return working together: [Source: php.net]

return.php

<?php

$var = 'PHP';

return $var;

?>

noreturn.php

<?php

$var = 'PHP';

?>

testreturns.php

<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>

Update

To only print a item from the array, you can use the indices. In your case:

<?php

$filepath="where_my_destination_file_sits";

define('OK', True); $c = include_once($filepath); print_r($c);
echo $c['titulo']; // print only the title

?>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!