【问题标题】:Handling JSON API response in PHP for data storage as variable在 PHP 中处理 JSON API 响应以将数据存储为变量
【发布时间】:2015-12-29 02:02:04
【问题描述】:

我需要将 JSON API 响应中的每个单独的值存储为一个变量,这样我就可以将它们存储在 MySQL 中。

在回显 id 时,我能够访问此处显示的顶级数据,但似乎无法访问嵌套数据,例如 name>text。

我是 API 使用的新手,因此感谢任何帮助。

<?php
 include("restclient.php");



 $api = new RestClient(array(
    'base_url' => "https://www.eventbriteapi.com/v3", 
));
$result = $api->get("/events/" . $_POST['id_eventbrite'] . "/?token=MYTOKENISHERE");


echo $result['id'];


?>

【问题讨论】:

    标签: php mysql json api parsing


    【解决方案1】:

    首先,您需要创建一个包含 Json 结果的相应列的表。然后,您只需生成一个查询并将值放置到位。例如,假设您的 Json 结果是这样的

    • 身份证号:1234
    • 姓名:乔希
    • 年龄:25

    你需要创建对应的表

    CREATE TABLE person ( id int, name varchar(25), age int);
    

    查询应该是这样的:

    INSERT INTO person (id, name, age) VALUES(?,?,?);
    

    要绑定数据,您将执行以下操作:

    $stmt = $mysqli->prepare("INSERT INTO person (id, name, age) VALUES(?,?,?)");
    $stmt->bind_param($response['id'], $response['name'], $response['age']);
    

    然后你执行查询并完成。

    有关参数绑定的详细信息,请查看 php 文档

    http://php.net/manual/en/mysqli-stmt.bind-param.php

    【讨论】:

    • 谢谢,虽然我的问题不在于 MySQL 插入。我无法访问嵌套数据。我可以很好地访问 ID,但不能访问事件标题。例如:{"name": { "text:": THE EVENT TITLE},
    • 我明白了...在这种情况下,使用 $myData=json_decode($YourJsonString, true);获取数据数组...然后像多维数组一样访问它 $myData['name']['text']
    【解决方案2】:

    Api 结果或 json 或 xml,你应该解析它。如果 json 使用var_dump(json_decode($result, true)); 如果xml使用json_decode(json_encode(simplexml_load_string($result)),true);

    【讨论】:

    • 它来自 Eventbrite API。我试过了,它只返回NULL。 &lt;?php include("restclient.php"); $api = new RestClient(array( 'base_url' =&gt; "https://www.eventbriteapi.com/v3", )); $result = $api-&gt;get("/events/" . $_POST['id_eventbrite'] . "/?token=KEY"); var_dump(json_decode($result, true)); echo $result['name']['text']; ?&gt;
    • 请做 var_dump($result);并将结果写在这里。
    • 它说字符太多。基本上,它在我的原始代码中正确获取了 id,但不会显示二级字段。我正在尝试显示事件的标题,该标题在名称下,然后是文本。例如:{"name": { "text:": THE EVENT TITLE},
    • $res = json_decode($result, true); $title = $res['name]['text];试试这个希望对你有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多