【问题标题】:how to get the content from a txt file into an array如何将txt文件中的内容获取到数组中
【发布时间】:2020-12-09 19:58:25
【问题描述】:

出于某种原因,我想将键和值从关联数组中分离出来,然后从 txt 文件中读取:

以下是我所拥有的

// translations
$lang = array(
    'All Articles' => 'Alle Artikelen',
    'Page' => 'Pagina',
    'from' => 'van'         
);

现在我想这样改变它:

$lang = array(
    file_get_contents("translations.txt"); // read the associative array
);

translations.txt 仅包含:

'All Articles' => 'Alle Artikelen',
'Page' => 'Pagina',
'from' => 'van', 

这不起作用。当它们存储在上面的 txt 文件中时,我如何读出键/值对?

【问题讨论】:

    标签: php arrays file-get-contents


    【解决方案1】:

    这是不可能获取文件内容并直接分配给数组的。您需要解析文件,提取行,然后提取键和值。

    $str = file_get_contents("translations.txt");
    $lang = [];
    foreach (explode("\n", $str) as $line)
    {
        if (strpos($line, '=>') === false)
        {
            continue;
        }
    
        list($key, $value) = explode('=>', $line);
        $lang[trim($key,'\' ')] = trim(trim($value), '\',');
    }
    

    使用explode根据换行符提取行(\n)。

    if (strpos($line, '=>') === false) 是一个用于避免空行(通常是文件结尾)错误的控件


    最好使用json文件:

    translations.json

    {"All Articles":"Alle Artikelen","Page":"Pagina","from":"van"}
    

    和php代码:

    $lang = json_decode(file_get_contents(public_path('lang.json')), true);
    var_dump($lang);
    

    【讨论】:

    • 我没有考虑过 json 但这确实是一个非常好的选择!谢谢
    【解决方案2】:

    这可能很危险。它将执行文件中的代码。

    eval(
      '$lang = array('.
        file_get_contents("translations.txt"). // read the associative array
      ');'
    );
    echo '<pre>';
    var_dump($lang);
    

    输出:

     array(3) {
      ["All Articles"]=>
      string(14) "Alle Artikelen"
      ["Page"]=>
      string(6) "Pagina"
      ["from"]=>
      string(3) "van"
    }
    

    【讨论】:

    • eval 函数可能很危险
    猜你喜欢
    • 2012-11-04
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多