如何访问JSON对象并插入数据库

时间:2016-01-26 03:00:41

标签: php mysql json

我想访问一个与我通常不同的JSON格式。

通常我会得到如下的JSON:

{
kind: "youtube#searchListResponse",
etag: ""stbstbsts"",
nextPageToken: "CAUQAA",
pageInfo: {
totalResults: 1000000,
resultsPerPage: 5
},
items: [
{
kind: "youtube#searchResult",
etag: ""pWoriJ5rlTq3315otdsHvMzLHR4"",
id: {
kind: "youtube#channel",
channelId: "UCbFnGyIcAhDrj-90OzvI7kw"
},
snippet: {
publishedAt: "2013-07-11T06:09:13.000Z",
channelId: "UCbFnGyIcAhDrj-90OzvI7kw",
title: "Oh My Disney",
description: "Videos for Disney lovers, by Disney lovers.",
thumbnails: {
default: {
url: "https://yt3.ggpht.com/-RpvvvIX2cL8/AAAAAAAAAAI/AAAAAAAAAAA/22QzVC_ihE4/s512-c-k-no/photo.jpg"
},
medium: {
url: "https://yt3.ggpht.com/-RpvvvIX2cL8/AAAAAAAAAAI/AAAAAAAAAAA/22QzVC_ihE4/s512-c-k-no/photo.jpg"
},
high: {
url: "https://yt3.ggpht.com/-RpvvvIX2cL8/AAAAAAAAAAI/AAAAAAAAAAA/22QzVC_ihE4/s512-c-k-no/photo.jpg"
}
},
channelTitle: "OhMyDisney",
liveBroadcastContent: "none"
}
},
{
kind: "youtube#searchResult",
etag: ""u4/3yClYSRlqGt3fuhXIOAwxFZWxB4"",
id: {
kind: "youtube#video",
videoId: "y8tDrJj-uyQ"
},
...

并使用

$arr = array();
foreach (json_decode($response) as $item){
  $post = $item->snippet->description;

  $arr[] = array(
           "post" => htmlspecialchars($post),
           );
/* script to insert database here */
}

从上面的JSON输出我可以访问它并将其插入数据库。 现在,我们回答我的问题。我有这个代码。

我的代码:

$appear = "http://suggestqueries.google.com/complete/search?client=firefox&q=Disney";
function get_curl($url) {
    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
        $output = curl_exec($ch);
        echo curl_error($ch);
        curl_close($ch);
        return $output;
    } else {
        return file_get_contents($url);
    }
}
$response = get_curl($appear);

输出:

[
  "disney",
  [
     "disney store",
     "disney",
     "disney world",
     "disneyland",
     "disney cruise",
     "disney movies",
     "disney channel",
     "disney games",
     "disneyland paris",
     "disney on ice"
  ]
]

目标:

"disney store" -> insert this word to the db
"disney"       -> insert this word to the db 
"disney world" -> insert this word to the db

怎么做?

1 个答案:

答案 0 :(得分:1)

这些是您要寻找的值,我让您添加数据库INSERT / UPDATE代码

echo $response['disney']['disney store'];
echo $response['disney']['disney'];
echo $response['disney']['disney world'];