2015-10-01 76 views
1

我需要將來自JSON API響應的每個單獨的值存儲爲一個變量,以便我可以將它們存儲在MySQL中。在PHP中處理JSON API響應數據存儲爲變量

我能夠在回顯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']; 


?> 
+0

的[我如何從JSON中提取數據與PHP?(可能的複製http://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) –

回答

2

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

+0

它來自Eventbrite API。我試過這個,它只是返回NULL。 '<?php include(「restclient.php」); $ array =( 'base_url'=>「https://www.eventbriteapi.com/v3」, )); $ result = $ api-> get(「/ events /」。$ _POST ['id_eventbrite']。「/?token = KEY」); var_dump(json_decode($ result,true)); echo $ result ['name'] ['text']; ?>' –

+0

請做var_dump($ result);並在此寫入結果。 –

+0

它說有太多的字符。基本上,它是在我的原始代碼中正確提取ID,但不會顯示第二級字段。我試圖顯示事件的名稱,然後是文本。例如:'{「name」:{「text:」:EVENT TITLE},' –

0

首先,您需要創建一個包含Json結果相應列的表。然後,您只需生成一個查詢並將這些值放置就位。例如,讓我們說你的JSON結果是這樣

  • ID: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

+0

謝謝,雖然我的問題不在MySQL插入。我無法訪問嵌套的數據。我可以訪問ID很好,但不是事件標題。例如:'{「name」:{「text:」:事件標題},' –

+0

我看到...在這種情況下,使用$ myData = json_decode($ YourJsonString,true);獲取你的數據數組......然後簡單地訪問它像一個多維數組$ myData ['name'] ['text'] – PekosoG