1
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

4 回答 4

0

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

        }
    $response = $posts;

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

?>`

于 2013-06-28T14:46:30.863 回答
0
$json_data = json_encode($response);
$filename ="yourfilename.json";
header('Content-type: application/json');
header('Content-Disposition: attachment; filename='.$filename);
echo $json_data ;

这是你想要的。

于 2013-06-28T07:13:11.577 回答
-1

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

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

mysql_fetch_object
于 2013-06-28T06:24:24.767 回答
-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"纹身是一种身体修饰形式,通过将不可磨灭的墨水注入皮肤真皮层来改变色素。"},} "title":"dog","author":"lakmal","article"家犬 (Canis lupus familiaris)[2][3] 是灰狼 (Canis lupus) 的一个亚种,是犬科的成员哺乳动物目食肉目科。术语“家犬”通常用于驯化和野生品种。“},}”标题“:”猫”,”作者”:“chamikara”,“文章”家猫[1][2](Felis catus[2] 或 Felis silvestris catus[4])是一种小型的、通常是毛茸茸的、驯养的肉食性哺乳动物。当作为室内宠物饲养时,它通常被称为家猫,[6] 或者在不需要区分时简称为猫"},}"title":"Automobile","author":"lakmal","article"汽车、autocar、motor car 或 car 是用于运送乘客的轮式机动车辆,它还带有自己的发动机或电动机。该术语的大多数定义都指定汽车主要在道路上行驶,具有 se"}, }}该术语的大多数定义都指定汽车主要在道路上行驶,具有“},}}该术语的大多数定义都指定汽车主要在道路上行驶,具有“},}}

于 2013-06-28T14:43:30.680 回答