如何从文本文件读取数组? [英] How to read array from text file?

查看:92
本文介绍了如何从文本文件读取数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用php中的file_put_contents()将数组存储在txt文件中,而php数组在文本文件中写入成功同时又如何将文本文件读入php中?

I have stored array in txt file using file_put_contents() in php, php array write successfullu in text file as same time how to read that text file into php?

<?php
$arr = array('name','rollno','address');
file_put_contents('array.txt', print_r($arr, true));
?>

上述php成功写入文本文件.我想在php中读取该文本文件?

The above php write text file in successfully. i want read that text file in php?

推荐答案

如果计划在数组中重用这些相同的值,则可以在创建该数组文件时使用var_export.

If you plan on reusing those same values inside the array, you could use var_export on creating that array file instead.

基本示例:

$arr = array('name','rollno','address');
file_put_contents('array.txt',  '<?php return ' . var_export($arr, true) . ';');

然后,当需要使用这些值时,只需使用include:

Then, when the time comes to use those values, just use include:

$my_arr = include 'array.txt';
echo $my_arr[0]; // name

或者只使用一个简单的JSON字符串,然后进行编码/解码:

Or just use a simple JSON string, then encode / decode:

$arr = array('name','rollno','address');
file_put_contents('array.txt',  json_encode($arr));

然后,当您需要时:

$my_arr = json_decode(file_get_contents('array.txt'), true);
echo $my_arr[1]; // rollno

这篇关于如何从文本文件读取数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆