如何在PHP中将JSONARRAY转换为JSON对象并另存为JSON文件


how to convert jsonarray to jsonobject in php and save as json file

require_once("conect.php");
$sqlString="SELECT * FROM articles;";
$response = array();
$posts = array();
$query=mysql_query($sqlString) or die (mysql_error());
    while ($row=mysql_fetch_array($query)){
        $title =$row["title"];
        $author =$row["author"];
        $article =$row["article"];
        $posts[] = array('title'=> $title, 'author'=> $author, 'article'=> $article);
    }
$response['posts'] = $posts;
$fp = fopen('json'results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);`

结果。。。

{"posts":[{"title":"tatoo","author":"lakmal","article":"A tattoo is a ."},  
{"title":"dog","author":"lakmal","article":"The domestic dog"},  
{"title":"cat","author":"chamikara","article":"The domestic"},  
{"title":"Automobile","author":"lakmal","article":"An automobile"}]}

我希望它另存为 JSON 对象

$json_data = json_encode($response);
$filename ="yourfilename.json";
header('Content-type: application/json');
header('Content-Disposition: attachment; filename='.$filename);
echo $json_data ;

这是你要找的吗?

' $title, 'author'=

> $author, 'article'=> $article(;

        }
    $response = $posts;
    $fp = fopen('results.json', 'w');
    fwrite($fp, json_encode($response));
    fclose($fp);    

?>'

mysql 结果作为对象获取。不要费心转换它。

http://php.net/manual/en/function.mysql-fetch-object.php

mysql_fetch_object

我找到了答案

<?php
        require_once("conect.php");
        $jsonData="[{";
        $sqlString="SELECT * FROM articles;";
        $query=mysql_query($sqlString) or die (mysql_error());
            while ($row=mysql_fetch_array($query)){
                $title =$row["title"];
                $author =$row["author"];
                $article =$row["article"];
                $jsonData.='"title":"'.$title.'","author":"'.$author.'","article"'.$article.'"},';      
                $jsonData.="{";         
            }
        $jsonData = chop ($jsonData, ",");
        $jsonData.="]";

        $fp = fopen('results.json', 'w');
        fwrite($fp,json_encode($jsonData));
        fclose($fp) 
?>`

生产:

{"title":"tatoo","author":"lakmal","article"纹身是一种身体修饰形式,通过将不可磨灭的墨水插入皮肤的真皮层以改变色素而制成。"家犬"一词通常用于驯养和野生品种。"},}"title":"cat","author":"chamikara","article"家猫[1][2](Felis catus[2]或Felis silvestris catus[4](是一种小型,通常毛茸茸的,驯养的,肉食性的哺乳动物。当它作为室内宠物饲养时,它通常被称为家猫,[6]或者当不需要distinguis时简称为猫"},}"title":"汽车","作者":"lakmal","article"汽车,汽车,汽车或汽车是用于运送乘客的轮式机动车辆,它也带有自己的发动机或电机。该术语的大多数定义都指定汽车主要设计为在道路上行驶,以具有se"},}}