如何在php中将jsonarray转换为jsonobject并保存为json文件

时间:2013-06-28 06:20:41

标签: php javascript json

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"}]}

我希望它保存为jsonobject

4 个答案:

答案 0 :(得分:0)

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

这就是你要找的东西。

答案 1 :(得分:0)

`$ title,'author'=> $ author,'article'=> $文章);

        }
    $response = $posts;

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

>`

答案 2 :(得分:-1)

将mysql结果作为对象获取。不要打扰转换它。

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

mysql_fetch_object

答案 3 :(得分:-2)

我找到了答案

<?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”纹身是一种身体修饰形式,通过在皮肤的真皮层插入不可磨灭的墨水来改变色素。 },“”标题“:”狗“,”作者“:”lakmal“,”文章“家犬(Canis lupus familiaris)[2] [3]是灰狼(Canis lupus)的一个亚种,成员哺乳动物食肉目的Canidae家族。家养犬通常用于家养和野生品种。“},”“标题”:“猫”,“作者”:“chamikara”,“文章”家猫[1] [2](Felis catus [2]或Felis silvestris catus [4])是一种小型的,通常是毛茸茸的,驯养的和食肉的哺乳动物。当它被保存为室内宠物时,它通常被称为housecat,[6]或者当没有必要区分时只是猫“},}”title“:”Automobile“,”author“:”lakmal“,”article“汽车,汽车,汽车或汽车是用于运输乘客的轮式机动车,其也带有自己的发动机或电动机。该术语的大多数定义规定汽车设计为主要在道路上行驶,具有se“}, }}