2017-06-21 110 views
0

我有一个超过10K的json文件的目录,我需要解析它们。解析函数适用于1个文件,但我看不到如何循环目录中的每个文件。如何`file_get_contents()`多个文件?

CONTROLER:

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 '); 
} 

我试图​​3210功能,但不保存任何循环结束。

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

+1

使用文件系统的symfony组件到该目录中读取所有文件,然后得到每个文件的内容。 –

+0

谢谢我只是看着它的文档,它可能是一个很好的解决方案,我学到了一些东西 – Gy0m

回答

0

我倾向于使用DirectoryIterator来循环目录中的文件,因为它为您提供了所有可能执行的各种解析的内置方法。只是目录名实例,然后遍历它:

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

这个解决方案似乎是一个很好的,但现在我得到一个错误'警告:为foreach()'提供的无效参数为我的其他循环,在 – Gy0m

+0

之前工作正常 –

+0

它是'foreach($ array作为$ item){' – Gy0m

相关问题