【问题标题】:How to `file_get_contents()` multiple files?如何`file_get_contents()` 多个文件?
【发布时间】:2017-06-21 13:36:49
【问题描述】:

我有一个包含超过 10K json 文件的目录,我需要全部解析它们。解析函数对 1 个文件非常有效,但我看不到如何循环目录中的每个文件。

控制器:

 public function parseFile()
{
    $em = $this->getDoctrine()->getManager();
    $em->getRepository('NcstoxBundle:JsonTextMining');

    foreach (glob('*.json') as $file) {

        set_include_path('/home/landreau/workspace/NCSTOX/web/assets/json/sample-json');
        $json = file_get_contents($file, FILE_USE_INCLUDE_PATH);
        $array = json_decode($json, true);
        var_dump($json);
        print_r($array);


        foreach ($array as $item) {
            $jsonTextMining = new JsonTextMining();
            $jsonTextMining->setSolrId($item['id']);
            $jsonTextMining->setOriginalPaper($item['Original_paper']);
            $jsonTextMining->setAnnotatedFile($item['Annotated_file']);
            $jsonTextMining->setTitle($item['Title']);
            foreach ($item['Molecule'] as $mol) {
                $jsonTextMining->setMoleculeName($mol['Main name']);
            }
            $jsonTextMining->setSynonymName($item['Molecule'][0]['Synonyms']);
            $jsonTextMining->setKeyword($item['ToxKeywords']);
            $jsonTextMining->setImportantSentence($item['Important_sentences'][0]);


            $em = $this->getDoctrine()->getManager();
            $em->persist($jsonTextMining);
        }
    }
    $em->flush();


    return new Response('Saved new document with id ');
}

我尝试glob() 函数,但循环结束时没有保存任何内容。

是否有人知道更好的语法来遍历目录中的所有文件,然后 file_get_contents() 他们?

【问题讨论】:

  • 使用 Filesystem symfony 组件读取该目录下的所有文件,然后获取每个文件的内容。
  • 谢谢,我刚刚查看了有关它的文档,这可能是一个很好的解决方案,我学到了一些东西

标签: php json symfony


【解决方案1】:

我更喜欢使用DirectoryIterator 循环目录中的文件,因为它为您提供了用于您可能进行的所有各种解析的内置方法。只需使用目录名称对其进行实例化,然后对其进行迭代:

foreach (new DirectoryIterator('/path/to/files') as $file) {
    if ($file->getExtension() === 'json') {
        $array = json_decode(file_get_contents($file->getPathname()), true);
        ....
    }
}

【讨论】:

  • 这个解决方案似乎是一个不错的解决方案,但现在我收到一个错误Warning: Invalid argument supplied for foreach(),因为我的另一个循环在之前运行良好
  • 这是`foreach ($array as $item) {`
  • 那么$array 不是数组,这意味着json_decode() 失败或JSON 文件不包含数组。
  • 我认为这可能是一个(或多个)负责的 json 文件,因为使用您的解决方案我可以用大约 300 个文件填充数据库。
【解决方案2】:

您可以使用The Finder Component

【讨论】:

  • 是的,它支持 glob。添加代码示例将有助于获得更多支持。 ;)
  • 我不确定这是不是一个答案 - 看起来更像是一个仅链接的软件推荐,可能更好地放在问题下方作为评论。
猜你喜欢
  • 2015-04-01
  • 1970-01-01
  • 2018-12-28
  • 2014-09-24
  • 1970-01-01
  • 2012-05-18
  • 2014-02-17
  • 2016-11-27
  • 2020-10-01
相关资源
最近更新 更多