无法在php中解析api的json响应

时间:2017-04-18 11:32:00

标签: php json

我试图在php中解析json的响应:url:

https://en.wikivoyage.org/w/api.php?action=query&prop=revisions&rvprop=content&format=jsonfm&titles=Ladakh

Fot解析,我写了代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="robots" content="noindex">

    <title>Upload</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <style type="text/css">
        @import url(http://fonts.googleapis.com/css?family=Open+Sans:400,700,300);
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,700,300);
body {
    font: 12px 'Open Sans';
}
.form-control, .thumbnail {
    border-radius: 2px;
}
.btn-danger {
    background-color: #B73333;
}

body {
  font-size: 80%;
  padding: 20px;
}

.center-block {
  float: none;
  margin: 0 auto;
}

main {
  position: relative;
  background: white;
  height: 200px;
  width: 60%;
  margin: 0 auto;
  padding: 20px;
  resize: both;
  overflow: auto;
}

main div {
  background: black;
  color: white;
  width: 200px;
  height: 100px;
  margin: -70px 0 0 -120px;
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 20px;
}

/* File Upload */
.fake-shadow {
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}
.fileUpload {
    position: relative;
    overflow: hidden;
}
.fileUpload #upload_form {
    position: absolute;
    top: 0;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 33px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}
.img-preview {
    width: 100%;
}

.container>.row>.col-md-6 {
  margin: 0 auto;
}
    </style>

    <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>
<body>
  <div class="container">
      <div class="row justify-content-center">
    <div class="col-md-6 center-block">
        <div class="form-group">
              <div class="main-img-preview center-block">
                <img class="thumbnail img-preview" src="http://farm4.static.flickr.com/3316/3546531954_eef60a3d37.jpg" title="Preview Logo">
              </div>
              <div class="input-group">
                <input id="fakeUploadLogo" class="form-control fake-shadow" placeholder="Select Image" disabled="disabled">
                <div class="input-group-btn">
                  <div class="fileUpload btn btn-danger fake-shadow">
                    <span><i class="glyphicon glyphicon-upload"></i> Upload Image</span>
                      <form id="image_form" action="upload_image" method="post">
                    <input class="attachment_upload" id="upload_form" name="image" type="file" enctype="multipart/form-data">
                    </form>
                  </div>
                </div>
              </div>
            </div>
    </div>
</div>
      </div>
  <script type="text/javascript">
  $(document).ready(function() {
    var brand = document.getElementById('upload_form');
    brand.className = 'attachment_upload';
    brand.onchange = function() {
        document.getElementById('fakeUploadLogo').value = this.value.substring(12);
    };

    function AKUpload(input) {
            var xmlHttpRequest = new XMLHttpRequest();
            xmlHttpRequest.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    window.location.replace(this.responseText);
               }
            };
            xmlHttpRequest.open("POST", '/upload_image', true);
            var formData = new FormData();
            formData.append("file", input.files[0]);
            xmlHttpRequest.send(formData);
            console.log(xmlHttpRequest.response);

    }
    $("#upload_form").change(function() {
        AKUpload(this);
    });
});



  </script>
</body>
</html>
除了警告之外,它只打印:

消息:为foreach()提供的参数无效

我在这里错过了什么吗?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

那是因为你需要传递format参数:

format=json

当你传递它时,格式= jsonfm会给你enter image description here

您的网址应为: https://en.wikivoyage.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=Ladakh

<强>更新

您需要使用的代码有点不对:

$parsed_data = $parsed_json['query']['pages']['18687']['revisions'];

而不是$parsed_data = $parsed_json['batchcomplete']['query']['pages']['18687']['revisions'];

因为您的JSON解码数组是这样的:

Array
(
    [batchcomplete] => 
    [query] => Array
        (
            [pages] => Array
                (
                    [18687] => Array
                        (
                            [pageid] => 18687
                            [ns] => 0
                            [title] => Ladakh
                            [revisions] => Array
                                (
                                    [0] => Array
                                        (

您可以使用以下行检查数据:

echo '<pre>';
print_r($parsed_json);
die;

答案 1 :(得分:0)

代码中的问题是您正在访问此代码 $parsed_json['batchcomplete']['query']['pages']['18687']['revisions'] $parsed_json['batchcomplete']不是数组string

$parsed_json['query']['pages']['18687']['revisions']

所需的更改:

  1. 改为循环format=json

  2. 更改网址<?php ini_set('display_errors', 1); $json_string = file_get_contents("https://en.wikivoyage.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=Ladakh"); $parsed_json = json_decode($json_string, true); $parsed_data = $parsed_json['query']['pages']['18687']['revisions']; foreach ($parsed_data as $key => $value) { echo $value['*']; }

  3. 中的格式

    试试这个希望它会正常工作......

    String jsonString = "Your Json Data";
      JSONObject  jsonRootObject = new JSONObject(jsonString );  
    JSONArray friendsArray = jsonRootObject .getJSONArray("Friends");
    
    ArrayList<FriendList > friendsList = new ArrayList<FriendList >();
    
    
    for(int friendsLen = 0 ;friendsLen  < friendsArray .length() ; friendsLen ++){
    FriendList userNameObj = new UserName();
    JSONObject jsonObj = jsonRootObject.getJSONObject(friendsLen )  ;
    String Username = jsonObj.getString("Username"); 
    userNameObj .setUserName(Username ); 
    friendsList .add(userNameObj );
    }