PHP ile. Json dosyası oluşturmak nasıl?

5 Cevap php
CREATE TABLE Posts
{
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
url VARCHAR(200)
}

json.php code

<?php
$sql=mysql_query("select * from Posts limit 20");
echo '{"posts": [';
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
echo '

{

"title":"'.$title.'",

"url":"'.$url.'"

},'; 
}
echo ']}';

?>

I results.json dosyası oluşturmak zorundayız.

5 Cevap

İşte bir örnek kod:

<?php 
$sql=mysql_query("select * from Posts limit 20"); 

$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) 
{ 
$title=$row['title']; 
$url=$row['url']; 

$posts[] = array('title'=> $title, 'url'=> $url);

} 

$response['posts'] = $posts;

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


?> 

Yerine yansımaları bir diziye getirilen değerleri yerleştirin.

Kullan file_put_contents() ve $rows veri ise, json_encode($rows) bu dosyaya yerleştirin.

Siz sadece json_encode function of php and save file with file handling functions such as fopen and fwrite kullanabilirsiniz.

Daha sonra bir dosyaya yazmak json oluşturmak için PHP'nin json methods kullanın fwrite.

Dinamik kayıtları çekiyorsun Eğer bir json temsilini oluşturur ve bir dosya her zaman oluşturmak değil 1 php dosyası var ve bu iyi.

my_json.php

$array = array(
    'title' => $title,
    'url' => $url
);

echo stripslashes(json_encode($array)); 

Sonra komut dosyasının yolunu ayarlamak my_json.php