2017-10-07 120 views
0

我想从使用PHP JsonReader的大型和嵌套JSON文件中提取数据,并将其放入.csv。我的问题是:使用PHP JsonReader从大型嵌套JSON文件中提取数据

  1. 打印出来的密钥与foo_一列开始
  2. 打印出的其他对象的值在嵌套文件

我想要的CSV表this。不知何故,我没有得到期望的结果,但我知道我有一个想法。这里是my dummy file

这里是我的代码:

<?php 
require_once 'C:/xampp/htdocs/json/pcrov/vendor/autoload.php'; 
use \pcrov\JsonReader\JsonReader; 
ini_set("max_execution_time", 0); 
$reader = new JsonReader(); 
$reader->open("jsonfile.json"); 
$fo = fopen("csvfile.csv", "w"); 
fputs($fo, "name, companyID, ultimateHoldingCompany".PHP_EOL); 
while ($reader->read(strpos($key, "foo__"))) { 
    // I want to loop through the key that contains foo_ and print the key name 
    $companyID = null; 
    $entityName = null; 
    $uhc = null; 
    $companyID = $key 
    $entityName = $reader->value(); 
    $UltimateHoldingCompany = $reader['ultimateHoldingCompany']['name']- 
    >value; 
    fputs($fo, 
    $entityName.",".$companyID.",".$UltimateHoldingCompany.PHP_EOL); 
    } 
    $reader->close(); 
    ?> 

回答

0

我已经测试了以下使用此dummy jsonfile的代码,它完美地回答我张贴的问题。

<?php 
require_once 'C:/xampp/htdocs/json/pcrov/vendor/autoload.php'; //make sure 
that this is a correct file path 
use \pcrov\JsonReader\JsonReader; 
ini_set("max_execution_time", 0); 
$reader = new JsonReader(); 
$reader->open("jsonfile.json"); 
$fo = fopen("csvfile.csv", "w"); 
fputs($fo, "name, companyID, uhc".PHP_EOL); 
{ 
    if (preg_match('/^foo_/', $reader->name())){ //To retreive keys that 
// starts with `foo_`, wildcard is employed here using regular expression 
// function in php. 
    $companyID = $reader->name(); 
    $companyID1 = str_ireplace("foo_","",$companyID); // this line is 
// necessary in order to remove foo_ because what is needed in the output 
// is everything after `foo_`. 

    if ($reader->read("entityName")){ 
     $entityName = $reader->value(); 
     $entityName = str_ireplace(","," ",$entityName); //comma need to be 
// replaced because csv treats comma as a delimiter. if comma not removed, 
// csv pushes everything after comma to another column 
    } 

    if ($reader->read("ultimateHoldingCompany")){  
     $uhcName = null; 
     $uhc = $reader->value(); 
     if (empty($uhc)){ 
     } 
     else { 
      $uhcName = $uhc[0]['name']; 
      $uhcName = str_ireplace(","," ",$uhcName); //comma need to be 
// replaced because csv treats comma as a delimiter. if comma not removed, 
// csv pushes everything after comma to another column 
     } 

    }  

    fputs($fo, $companyID1.",".$entityName.",".$uhcName.PHP_EOL); 
    } 
    } 
$reader->close(); 
?>