doucuan5365 2013-08-07 00:54
浏览 37
已采纳

php从文件中的任何行检索值

I'm trying to grab a specific value out of a file and turn it into a variable. I've manged to figure this out, but there is a catch. I need to get the variable even if the file changes so I can't depend getting this value by reading a certain line from the file as it will change on a regular basis. Here is my file and code:

# the file.props contents:
color=red
height=tall
length=short
weight=heavy
size=small
shape-name=round

Php code:

<?php
$file = "/home/user/files/file.props";
$contents = file($file, FILE_SKIP_EMPTY_LINES);
$shape_name = substr(trim($contents[5]), 11);
?>

<?php echo "$shape_name"; ?>

The above works but only if "shape-name=round" is on line 6 of the file as I am using $contents[5] to get it. Is it possible to do this if the line the "shape-name=round" is constantly being altered? IE: tomorrow it will be on line 9, the next day it could be on line 4 etc... Basically I can't depend on what line "shape-name=round" is on but I need to grab it. Not sure I am describing this correctly so please let me know if I need to clarify anything.

  • 写回答

2条回答 默认 最新

  • doo58088 2013-08-07 01:04
    关注

    Maybe you mean something like this?

    foreach($contents as $line) {
        list($option, $value) = explode('=', $line);
        if ($option == 'shape-name') {
            $shape_name = $value;
        } elseif ($option == 'size') {
            $size = $value;
        }
        // you can include as many option as possible here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画