开发者

Create variable from print_r output [duplicate]

This question already has answers here: How create an array from the ou开发者_StackOverflow社区tput of an array printed with print_r? (11 answers) Closed 10 years ago.

How can i create variable from it's print_r output ? In other words, i'd like to know if something similar to my fictive var_import function exists in php ? var_import would be the inverse of var_export

He is a use case:

$a = var_import('Array ( [0] => foo [1] => bar )');
$output = var_export($a);
echo $output; // Array ( [0] => foo [1] => bar )

If such a function does not exist, is there a tool (or online tool) to do this ? I am also interested to do the same with var_dump output.

EDIT: The variable is only available as a print_r output (string). To clarify what i need, imagine the folowing situation: someone posts a some sample on the internet somewhere with a print_r output. To test his code, you need to import his print_r variable into your code. This is an example where var_import would be usefull.


Amusingly the PHP manual contains an example that tries to recreate the original structure from the print_r output:
print_r_reverse()
http://www.php.net/manual/en/function.print-r.php#93529

However it does depend on whitespace being preserved. So you would need the actual HTML content, not the rendered text to pipe it back in.

Also it doesn't look like it could understand anything but arrays, and does not descend. That would be incredibly difficult as there is no real termination marker for strings, which can both contain newlines and ) or even [0] and => which could be mistaken for print_r delimiters. Correctly reparsing the print_r structure would be near impossible even with a recursive regex (and an actual parser) - it could only be accomplished by guesswork splitting like in the code linked above.. (There are two more versions there, maybe you have to try them through to find a match for your specific case.)


Why don't you use var_export instead ?

var_export(array(1, 2, 3)); // array(1, 2, 3)

You can import var_export's output with eval(), however I would recommend you to avoid this function as much as possible.

The following functions are better for exporting and importing variables:

serialize() and unserialize():

$string = serialize(array(1, 2, 3));
$array = unserialize($string); // array(1, 2, 3);

Or json_encode() and json_decode():

$string = json_encode(array(1, 2, 3));
$array = json_decode($string);


You can wrap it in an output buffer:

ob_start();
print_r(array(1,2,3));
$arr = ob_get_clean();
echo $arr;

Ok so I misunderstood the first question. I think I have another solution which actually does answer your question:

<?php
$ar = array('foo','bar');
$p = print_r($ar, true);

$reg = '/\[([0-9]+)\] \=\> ([a-z]+)/';
$m = preg_match_all($reg, $p, $ms);

$new_ar = $ms[2];

echo "Your wanted result:\n";
print_r($new_ar);


If you want to import a var_export()'s variable, you can run the eval() function. Or if you save the contents into a file (with a return statement), you can use the return value of include() or require().

But I would rather use serialize() and unserialize() or json_encode() and json_decode().

define('EXPORT_JSON', 1);
define('EXPORT_SERIALIZE', 2);

function exportIntoFile($var, $filename, $method=EXPORT_JSON)
{
  if ( $method & EXPORT_JSON )
    file_put_contents( $filename, json_encode($var) );
  else if ($method & EXPORT_SERIALIZE)
    file_put_contents( $filename, serialize($var) );
}
function importFromFile($filename, $method=EXPORT_JSON)
{
  if ( $method & EXPORT_JSON )
    return json_decode( file_get_contents($filename) );
  else if ($method & EXPORT_SERIALIZE)
    return unserialize( file_get_contents($filename) );
}


I'm not good at regex to code the final trash removal. Here is how far I could get though:

$str = 'Array ( [0] => foo [1] => bar [2] => baz)';
$t1 = explode('(', $str);
$t2 = explode(')', $t1[1]);
$t3 = explode(' => ', $t2[0]);
unset($t3[0]);

print_r($t3);

output:

Array
(
    [1] => foo [1]
    [2] => bar [2]
    [3] => baz
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜