简体   繁体   中英

PHP read array declaration from file?

I've got a text file with an array declaration (actually an array of arrays) that I'm reading into my PHP using 'file_get_contents' . The PHP code is treating the contents that it reads from the file as a literal string, rather than creating an array. I need to actually create the array.

Example:

The file 'probe2.csv' contains the following text:

array(array(22, 296), array(43, 667), array(64, 1008), array(84, 1273), array(105, 1520), array(126, 1899), array(146, 2149))

My PHP is:

$s1 = array(array(22, 256), array(43, 524), array(64, 797), array(84, 1133), array(105, 1515), array(126, 1813), array(146, 2128));
$s2 = file_get_contents('probe2.csv');
print_r($s1);
echo "<p>";
print_r($s2);
echo "</p>";

The output is:

Array ( [0] => Array ( [0] => 22 [1] => 256 ) [1] => Array ( [0] => 43 [1] => 524 ) [2] => Array ( [0] => 64 [1] => 797 ) [3] => Array ( [0] => 84 [1] => 1133 ) [4] => Array ( [0] => 105 [1] => 1515 ) [5] => Array ( [0] => 126 [1] => 1813 ) [6] => Array ( [0] => 146 [1] => 2128 ) )

array(array(22, 296), array(43, 667), array(64, 1008), array(84, 1273), array(105, 1520), array(126, 1899), array(146, 2149))

I'm a bash guy, not a PHP guy, so I have no idea how to do this.

To make it work, you should you need to change it like this:

<?php
$s2 = array(array(22, 296), array(43, 667), array(64, 1008), array(84, 1273), array(105, 1520), array(126, 1899), array(146, 2149));

And then, in you main php file, just include it:

include('probe2.php');

If you have no control about the probe2 file, you can do this (it's bad practice, but works):

$temp = file_get_contents('probe2.csv');
eval('$s2 = ' . $temp . ';');

$s2 will have the right array from here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM