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条)

报告相同问题?