【问题标题】:PHP reading data input from a text filePHP从文本文件中读取数据输入
【发布时间】:2016-07-15 13:13:17
【问题描述】:

我有一个文本文件,我必须阅读并使用其中的数据。

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

如何以下列形式创建这些字符串的数组?

array(
    "name" => "number"
    ...
)

我试过这个:

$handle = fopen("file.txt", "r");
fscanf($handle, "%d %d", $name, $number);

然后呢?无论我尝试什么,它都只适用于第一行。

sam 99912222

【问题讨论】:

  • 没有名称/编号的行怎么办?

标签: php input output


【解决方案1】:

添加了具有两种输出类型的代码 - 忽略并包括没有名称-值对的行。在下面查看它们


此代码遍历每一行并仅获取同时具有namevalue (something[space]something)) 的代码:
//$lines = ... each line of the file in an array

$vals = array();
foreach($lines as $v){
    $tmp = explode(' ', $v);
    if(count($tmp) > 1){
        $vals[trim($tmp[0])] = trim($tmp[1]); // trim to prevent garbage
    }
}

print_r($vals);

它会输出这个:

Array
(
    [sam] => 99912222
    [tom] => 11122222
    [harry] => 12299933
)

查看代码here


如果您需要这些值,即使它们不是成对出现的,也可以这样做:

//$lines = ... each line of the file

$vals = array();
foreach($lines as $v){
    $tmp = explode(' ', $v);
    $name = '';
    $number = '';
    $tmp[0] = trim($tmp[0]);
    if(count($tmp) > 1){
        $name = $tmp[0];
        $number = trim($tmp[1]);
    }else{
        if(is_numeric($tmp[0])){
            $number = $tmp[0];
        }else{
            $name = $tmp[0];
        }

    }
    $vals[] = array(
        'name' => $name,
        'number' => $number
    );
}

print_r($vals);

还有输出:

Array
(
    [0] => Array
        (
            [name] => 
            [number] => 3
        )

    [1] => Array
        (
            [name] => sam
            [number] => 99912222
        )

    [2] => Array
        (
            [name] => tom
            [number] => 11122222
        )

    [3] => Array
        (
            [name] => harry
            [number] => 12299933
        )

    [4] => Array
        (
            [name] => sam
            [number] => 
        )

    [5] => Array
        (
            [name] => edward
            [number] => 
        )

    [6] => Array
        (
            [name] => harry
            [number] => 
        )

查看代码here

【讨论】:

  • 你们俩都有我的“赞成票”,因为你们花时间试图帮助我
【解决方案2】:

文件中的数据不一致,最好使用正则表达式来识别您从每一行获得的数据。

$lines = file('file.txt'); // this will open file and split them into lines
$items = array();
foreach($lines as $line){
   $name = null;
   $number = null;
   $nameFound = preg_match("|([A-Za-z]+)|", $line, $matches);
   if($nameFound){
      $name = $matches[0];
   }
   $numberFound = preg_match("|([0-9]+)|", $line, $matches);
   if($numberFound){
      $number = $matches[0];
   }

   $items[] = array('name' => $name, 'number' => $number);
}

然后在项目中你应该从文件中找到解析的数据。

要使其仅提取完整格式的数据,只需将带有正则表达式的行更改为一行:

$lines = file('file.txt'); // this will open file and split them into lines
$items = array();
foreach($lines as $line){
   $userFound = preg_match("/([A-Za-z]+) ([0-9]+)/", $line, $matches);
   if($userFound){
      $items[$matches[1]] = $matches[2];
   }

}

【讨论】:

  • 我对此进行了测试,但它似乎不起作用...https://eval.in/605956(请注意,我不是操作员)
  • $matches 中出现拼写错误立即尝试
  • 我在这个问题开始的输入形式是 $_fp = fopen("php://stdin", "r");我无法更改它,这就是我如何从该输入中接收数据的单一方法
  • 看看它是如何输出的,[1]=> array(2) { ["name"]=> string(3) "sam" ["number"]=> string(3) "sam" } [2]=> array(2) { ["name"]=> string(3) "tom" ["number"]=> string(3) "tom" } [3]=> array( 2) { ["name"]=> string(5) "harry" ["number"]=> string(5) "harry" } [4]=> 没有数字
  • 您必须首先弄清楚解析所有的目标是什么,或者只提取具有两个值的行或什么,因为基于此可能对您有所帮助。
【解决方案3】:

使用下面的算法,您可以简单地将文本文件内容的每一行解析为一个数组,其中每行的第一个字或数字作为键,第二个字作为值。当第二个单词或单词组不存在时,将 NULL 分配给该 Key。为了可重用性,这个算法被封装成一个函数。给你:

<?php

    function parseTxtFile($txtFile){
        $arrTxtContent      = [];

        if(!file_exists($txtFile)){ return null;}
        $strFWriteTxtData   = file_get_contents($txtFile);

        if(empty($strFWriteTxtData)){return null;}

        $arrFWriteInfo      = explode("\n", $strFWriteTxtData);

        foreach($arrFWriteInfo as $iKey=>$lineData){
            $arrWriteData   = explode(", ", $lineData);
            foreach($arrWriteData as $intKey=>$strKeyInfo){
                preg_match("#(^[a-z0-9_A-Z]*)(\s)(.*$)#i", $strKeyInfo, $matches);
                preg_match("#(^[a-z0-9_A-Z]*)(\s*)?$#i", $strKeyInfo, $matches2);
                if($matches) {
                    list(, $key, $null, $val)   = $matches;
                    if (!array_key_exists($key, $arrTxtContent)) {
                        $arrTxtContent[$key]    = $val;
                    }else{
                        $iKey   = $intKey + 1;
                        $key    = $key . "_{$iKey}";
                        $arrTxtContent[$key]    = $val;
                    }
                }else if($matches2) {
                    list(, $key, $null)   = $matches2;
                    if (!array_key_exists($key, $arrTxtContent)) {
                        $arrTxtContent[$key]    = null;
                    }else{
                        $key = preg_match("#_\d+#", $key, $match)? $key . $match[0] : "{$key}_1";
                        $arrTxtContent[$key]    =  null;
                    }
                }
            }
        }
        return $arrTxtContent;
    }

    var_dump(parseTxtFile(__DIR__ . "/data.txt"));

只需调用函数parseTxtFile($txtFile) 将路径传递给您的文本文件,它将返回一个如下所示的数组:

    array (size=7)
      3         => null
      'sam'     => string '99912222' (length=8)
      'tom'     => string '11122222' (length=8)
      'harry'   => string '12299933' (length=8)
      'sam_1'   => null
      'edward'  => null
      'harry_1' => null

希望这能有所帮助....

干杯和好运 ;-)

【讨论】:

    猜你喜欢
    • 2011-02-08
    • 1970-01-01
    • 2017-02-05
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多