将php输出转换为JSON

时间:2014-01-23 17:23:00

标签: php json

我有一个PHP脚本的以下输出:

one@gmail.com test1
two@gmail.com test2

由以下内容生成:

$i = 0;
  $header = array();
  while (!feof($handle)) {
    $buffer = fgets($handle, $chunk_size);
   if (trim($buffer)!=''){
      $obj = json_decode($buffer);

       echo $obj[0]." ".$obj[2]."<br>";

      $i++;
    }
  }
fclose($handle);

如何将脚本的输出转换为JSON格式:

{"emails":[{"email":"one@gmail.com","option":test1"},{"email":"two@gmail.com","option":test2"}]}

该脚本取自Mailchimp API,列出了列表的订阅者。 以下是供参考的脚本:

<?php
$apikey = '1234-us7';
$list_id = '1234';
$chunk_size = 4096; //in bytes
$url = 'http://us7.api.mailchimp.com/export/1.0/list?apikey='.$apikey.'&id='.$list_id.'&output=json';


/** a more robust client can be built using fsockopen **/
$handle = @fopen($url,'r');
if (!$handle) {
  echo "failed to access url\n";
} else {
  $i = 0;
  $header = array();
  while (!feof($handle)) {
    $buffer = fgets($handle, $chunk_size);
   if (trim($buffer)!=''){
      $obj = json_decode($buffer);
      if ($i==0){
        //store the header row
        $header = $obj;
      } else {
        //echo, write to a file, queue a job, etc.
       echo $obj[0]." ".$obj[2]."<br>";


       }
      $i++;
    }
  }

  fclose($handle);
}
?>

谢谢!

3 个答案:

答案 0 :(得分:1)

它似乎已经在JSON中,因为您正在使用json_decode来获取该输出。所以只是......停止使用json_decode

答案 1 :(得分:1)

正如@jessica已经提到的,看起来$ buffer是以JSON的形式出现的,因为你正在运行json_decode(&buffer)

但是,如果您想进行一些操作,请排列数据,以便构建如下数组:

$myArray = array(
    'emails' => array(
         array('email' => 'one@gmail.com','option' => 'test1'),
         array('email' => 'two@gmail.com','option' => 'test2'),
    )
);

然后:

echo json_encode(myArray);

使用你的代码,就像这样(未经测试):

$myArray = array();
$i = 0;
$header = array();
while (!feof($handle)) {

    $buffer = fgets($handle, $chunk_size);

    if (trim($buffer)!='') {

        $obj = json_decode($buffer);

        $myArray['emails'][] = array('email' => $obj[0],'option' => $obj[2]);

        $i++;
    }
}

fclose($handle);

echo json_encode($myArray);

答案 2 :(得分:0)

$i = 0;
$result = array();  //create a new array
  $header = array();
  while (!feof($handle)) {
    $buffer = fgets($handle, $chunk_size);
   if (trim($buffer)!=''){
      $obj = json_decode($buffer);

       //echo $obj[0]." ".$obj[2]."<br>";  //comment out this line
       $result[] = array('email' => $obj[0], 'option' => $obj[2]);  //push new obj to the array

      $i++;
    }
  }
fclose($handle);
echo json_encode(array('emails' => $result)); // convert to json format