如何使用PHP以下列格式解析来自txt文件的数据

时间:2016-01-27 13:26:44

标签: php parsing

如何使用php解析txt文件中的数据? 这是我的variables.txt文件

TITLE=Job=test
IMAGES=image1.jpg,image2.jpg,image3.jpg
IMAGES2=image3.jpg,image2.jpg,image1.jpg

这是html文件模板

<!DOCTYPE html>
<html>
    <head>
        <title>++TITLE++</title>
    </head>
    <body>
        <h1>++TITLE++</h1>
        <p>This is a template file where you have to swap the variables between the double plus signs (++VAR++) with the values in variables.txt.</p>
        <p>You should write a class that is the template engine. This engine should support the following functions: replace variables, include subtemplates, support loops.</p>
        <ul>
        --for ++IMAGES++ as IMAGE--
            <li>--include image.html with IMAGE--</li>
        --endfor--
        </ul>
        <ul>
        --for ++IMAGES2++ as IMAGE--
            <li>--include image.html with IMAGE--</li>
        --endfor--
        </ul>
    </body>
</html>

我有一个包含3张图片的图像文件夹image1.jpg,image2.jpg和image3.jpg

输出应该看起来像

作业=测试

  • image1.jpg here
  • image2.jpg here
  • image3.jpg

  • image3.jpg

  • image2.jpg here
  • image1.jpg here

1 个答案:

答案 0 :(得分:1)

我试过这样的事情;     

function parseText($text) {

    $exp = explode("\n", $text);
    $newDatas = array();

    foreach ($exp as $row) {
        if (strpos($row, "=") !== false) {
            $keyVals = explode("=", $row);
            $newDatas[$keyVals[0]] = $keyVals[1];
        }
    }

    return $newDatas;
}


function getTextKey($key, $explodeWith = "") {
    $text = "TITLE=Job=test\nIMAGES=image1.jpg,image2.jpg,image3.jpg\nIMAGES2=image3.jpg,image2.jpg,image1.jpg";
    if ($explodeWith == "") {
        $data = parseText($text)[$key];
    } else {
        $data = explode($explodeWith,  parseText($text)[$key]);

    }
    return $data;
}

?>

<!DOCTYPE html>
<html>
    <head>
        <title><?php echo getTextKey("TITLE"); ?></title>
    </head>
    <body>
        <h1><?php echo getTextKey("TITLE"); ?></h1>
        <p>This is a template file where you have to swap the variables between the double plus signs (++VAR++) with the values in variables.txt.</p>
        <p>You should write a class that is the template engine. This engine should support the following functions: replace variables, include subtemplates, support loops.</p>
        <ul>
        <?php
        foreach(getTextKey("IMAGES", ",") as $image) 
        { 
        ?>
            <li><?php include($image.".html"); ?></li>
        <?php 
        }
        ?>
        </ul>
        <ul>
        <?php
        foreach(getTextKey("IMAGES2", ",") as $image) 
        { 
        ?>
            <li><?php include($image.".html"); ?></li>
        <?php 
        }
        ?>
        </ul>
    </body>
</html>