Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中解析类似CVS的文件并将其存储为字典_Php - Fatal编程技术网

在PHP中解析类似CVS的文件并将其存储为字典

在PHP中解析类似CVS的文件并将其存储为字典,php,Php,我正在生成的文本文件如下所示: ipaddress,host ipaddress,host ipaddress,host ipaddress,host ipaddress,host ... 如何读取此文件并将每一行存储为键值对 前 对于简单的解决方案: <?php $hosts = file('hosts.txt', FILE_SKIP_EMPTY_LINES); $results = array(); foreach ($hosts as $h) {

我正在生成的文本文件如下所示:

ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
...
如何读取此文件并将每一行存储为键值对

对于简单的解决方案:

<?php
    $hosts = file('hosts.txt', FILE_SKIP_EMPTY_LINES);
    $results = array();
    foreach ($hosts as $h) {
        $infos = explode(",", $h);
        $results[$infos[0]] = $infos[1];
    }
?>

尝试该功能



@airza,为什么?我不会在这里使用正则表达式,它是简单的字符串拆分。是的,那会更好。在你发布一个简单的问题之前做一些工作。至少说,“这就是我所拥有的,我做错了什么?”这不像是一个家庭作业完成网站。可能是重复的
$arr = file('myfile.txt');
$ips = array();

foreach($arr as $line){
  list($ip, $host) = explode(',',$line);
  $ips[$ip]=$host;
}
<?php
    $hosts = file('hosts.txt', FILE_SKIP_EMPTY_LINES);
    $results = array();
    foreach ($hosts as $h) {
        $infos = explode(",", $h);
        $results[$infos[0]] = $infos[1];
    }
?>
//open a file handler
$file = file("path_to_your_file.txt");

//init an array for keys and values
$keys= array();
$values = array();

//loop through the file
foreach($file as $line){

    //explode the line into an array
    $lineArray = explode(",",$line);

    //save some keys and values for this line
    $keys[] = $lineArray[0];
    $values[] = $lineArray[1];
}

//combine the keys and values
$answer = array_combine($keys, $values);
<?php
$handle = @fopen("ip-hosts.txt", "r");
$result = array();
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        $t = explode(',', $buffer);
        $result[$t[0]] = $t[1];
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
// debug:
echo "<pre>";
print_r($result);
echo "</pre>"
?>