如何从PHP上的本地文件夹/文件中获取数据并创建JSON数据

时间:2017-05-20 22:09:49

标签: php json foreach

我想在PHP上输出下面看起来像jasondata的jason数据。 folder是文件夹的名称,title位于info.txt的第一行。 info.txt位于该文件夹下。每个info.txt中有三行,这些行只是通过创建新行(不是逗号)来分隔。文件夹books和我的php文件位于同一文件夹下。我该如何编写PHP代码?谢谢。 我的PHP代码在这里;

function books(){

    $array = [];
    $story = glob("books/" . "*");

    foreach($story as $each){
        $title = file($each ."/info/txt", FILE_IGNORE_NEW_LINES);
        $output = array (
            "title" => $title[0],
            "folder" => $each #i would like to put the name of the folder here
            );
        array_push($array,$review);
    }
    print(json_encode($array));
}

Json数据应该是这样的;

{
    "books" : [
        {
         "title": "Harry Potter and the Prisoner of Azkaban",
         "folder": "harrypotter"
         },
        {
         "title": "The Hobbit",
         "folder": "hobbit"
         },
        ... (one entry like this for each folder inside books/)
    ]
}

1 个答案:

答案 0 :(得分:0)

使用DirectoryIterator或scandir函数,请尝试以下代码

$dirs   = '/directory/';
$dir    = new DirectoryIterator($dirs);
$array  = array();
foreach ($dir as $key => $fileinfo) {
    if ($fileinfo->isDir()) {
        //remove hidden files or dot files
        if ( $fileinfo->getBasename() === '.' || $fileinfo->getBasename() === '..' ) continue);

        //foldername 
        $array[$key]['folder'] = $fileinfo->getBasename();

        //title 
        $array[$key]['title'] = file($array[$key]['folder'].'/info.txt' ,  FILE_IGNORE_NEW_LINES);
    }
}

$json = json_encode($array);
print_r($json);

让我知道它是否有效。

<强>编辑 我尝试在我的本地主机上工作

$dirs   = 'books/';
$dir    = new DirectoryIterator($dirs);
$array  = array();
foreach ($dir as $key => $fileinfo) {
    if ($fileinfo->isDir()) {
        //remove hidden files or dot files
        if ( $fileinfo->getBasename() === '.' || $fileinfo->getBasename() === '..' ) continue;

        //foldername 
        $array[$key]['folder'] = $fileinfo->getBasename();

        //title 
        $array[$key]['title'] = file($dirs.'/'.$array[$key]['folder'].'/info.txt' ,  FILE_IGNORE_NEW_LINES);
    }
}

$json = json_encode($array);
echo '<pre>'.print_r($json, true).'</pre>';

<强>截图

enter image description here