【问题标题】:PHP for read txt file line just upon sign "#"仅在符号“#”时读取 txt 文件行的 PHP
【发布时间】:2011-06-20 15:16:05
【问题描述】:

我有这个txt文件结构:

"data";"data";"data";#;"my data";"my data";"my data"
"data";"data";"data";#;"my data";"my data";"my data"
"data";"data";"data";#;"my data";"my data";"my data"

我需要在# 符号之后读取此文件数据。 我的 PHP 代码只是为了阅读整行。

$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   $numlinha++;
   echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);

【问题讨论】:

标签: php text-files filehandle


【解决方案1】:

您可以使用strpos 函数查找行中第一个# 字符的位置。

$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   $cpos = strpos($line, '#');
   if ($cpos !== FALSE) {
       $line = substr($line, 0, $cpos);
   }
   $numlinha++;
   echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);

【讨论】:

  • 谢谢大家。非常有用的提示。还有一件事,我可以将每个数据值放在一个 $_SESSION 变量上,并为第一个 $_SESSION['peso'] 命名为第二个......?
【解决方案2】:
$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   $parts = explode("#", $line);
   $parts[0] // part before the # in this line
   $parts[1] // part behind the # in this line
   $numlinha++;
   echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);

【讨论】:

    【解决方案3】:

    您可以使用: $data = explode(";#;", $line); 然后对 $data[1] 而不是 $line 进行处理。

    这假设 ;#;每行都是唯一的...

    请注意,我相信,使用字符串位置测试 (strpos()) 和 substr() 来提取字符串的一部分会比仅使用您已经阅读的行并将其拆分为确切的已知分隔符更消耗资源,在这种情况下是;#;。

    发布的其他示例假设 # 将仅在该行中出现一次,或者至少该除法将是该行中的第一个 #。使用 ;#;会使它更加独特,如果您需要将结果分解为其他用途的值数组,则可以通过 str_getcsv() 函数处理您的结果。

    【讨论】:

      【解决方案4】:

      您可以使用explode函数,使用“#”分隔符将字符串分成两部分

      http://php.net/function.explode

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        • 1970-01-01
        • 2015-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多