PHP错误提取json文件

时间:2014-02-26 09:33:48

标签: php json web

有人可以帮助我的JSON文件无法显示的原因吗?我是JSON的初学者。这是我的代码,它只显示空白文档。我正在从这个网站http://contohprogramandroid.blogspot.com/2013/10/contoh-program-android-aplikasi-wisata.html学习本教程。非常感谢你。

运行代码时我的图像。 enter image description here

//this is the code webservice.php

<?php
class Database {
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db   = "wisata_jogja";
private $conn;

// constructor
function __construct() {
    try{
        $this->conn = new PDO( "mysql:host=".$this->host.";dbname=".$this->db, $this->user, $this->pass );
    }catch( PDOException $e ) {
        echo "error pdo $e";
    }
}


public function showAllData( $table ) {
    $sql ="SELECT * FROM $table";
    $q = $this->conn->query( $sql ) or die( "Failed !!" );
    while ( $r = $q->fetch( PDO::FETCH_ASSOC ) ) {
        $data[] = $r;
    }
    return $data;
}

}

$database = new Database();
$response = array();

if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
$response['location'] = array();

foreach ( $database->showAllData( 'lokasi' ) as $value ) {
    $kode = array();
    extract( $value );

    $kode['id'] = $id;
    $kode['nama'] = $nama;
    $kode['alamat'] = $alamat;
    $kode['gambar'] = $gambar;
    $kode['lat'] = $lat;
    $kode['lng'] = $lng;
    array_push( $response['location'], $kode );
}
echo json_encode( $response ); 
}
?>

2 个答案:

答案 0 :(得分:0)

您确定将GET变量“lokasi”传递给您的脚本吗?

否则,它不会通过if条件

  

if(isset($ _ GET ['get'])&amp;&amp; $ _GET ['get'] =='lokasi')

您可以通过尝试在if条件中转储变量或任何foobar数据来检查这一点,以验证代码是否走得那么远,例如:

if(isset($_GET['get'] ) && $_GET['get']=='lokasi') {
    $response['location'] = array();

    $myTest = array('test');
    var_dump($myTest); // Should display something on screen

    // The rest of your code here

答案 1 :(得分:0)

您的输出条件是:

if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {

因此,脚本不会输出任何JSON,因为不符合条件。

从屏幕截图中可以清楚地看到您缺少GET个参数。

在浏览器中将参数添加到网址:

http://localhost/wisata/webservice.php?get=lokasi

当条件不成立时采取替代行动总是好的。

你应该总是echo只是为了让你知道发生了什么:

if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
    //..............
    echo json_encode( $response ); 
}else{
    echo "cannot output JSON data: parameter is missing!!;
}