0

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.

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You should really consider using serialisation or a proper data format instead though, if you have the option. stackoverflow.com/questions/804045/… might help with choosing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.