简体   繁体   English

评估字符串作为数组

[英]eval string as an array

I have a .html file which contains the following: 我有一个.html文件,其中包含以下内容:

array('1', '786286', '45626');

That is literally all it contains. 这就是它所包含的全部内容。

In my code, I want to eval this and then print it: 在我的代码中,我想评估一下然后打印出来:

$code = file_get_contents('array.html');
$nums = eval($code);
print_r($nums);

However, it is not printing anything. 但是,它没有打印任何内容。

Any help would be greatly appreciated. 任何帮助将不胜感激。

First off, don't use eval() . 首先,不要使用eval() it's an EVIL function and should be avoided like the plague. 这是一种EVIL功能,应避免像瘟疫一样避免使用。

Secondly, it's not working, because you haven't written proper PHP code. 其次,它不起作用,因为您没有编写正确的PHP代码。 What your eval is doing is the literal equivalent of having a .php file which contains: 您的eval在做什么,实际上就是拥有一个.php文件,该文件包含:

<?php
array(1,2,3)

There's no assignment, there's no output, and there's no return . 没有分配,没有输出,也没有return There's simply an array being "executed" and then immediately being destroyed. 只是有一个数组被“执行”,然后立即被销毁。

What you should have is 你应该拥有的是

<?php
$arr = array(1,2,3)

so the array gets preserved. 这样就保留了数组。 Which means your eval should look more like: 这意味着您的评估应该更像:

$text = file_get_contents('...');
// option 1
eval("\$arr = $text");
      ^^^^^^^
print_r($arr);

// option 2
$foo = eval("return $text");
             ^^^^^^
print_r($foo);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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