使用php从url解析json并保存在mysql db中

时间:2017-08-21 06:13:03

标签: php json

我从某个网络服务

获得了JSON响应
{
  "success":true,
  "timestamp":1503291248,
  "quotes":{
    "SAD":"ABC",
    "LOVE":"XYZ",
    "FRIENDSHIP":"SOME",
    "ENMITY":"LOREM IPSUM",
    ... //indicates there are a lot more categories
  }
}

我尝试使用此脚本回显数据

<?php
    $url = 'MY_URL';
    $content = file_get_contents($url);
    $json = json_decode($content, true);

    foreach ( $json as $idx=>$json ) {
       echo $idx;
    }
?>

打印

successtermsprivacytimestampsourcequotes

但是获得空响应,如何在mySql中回显/保存上面的josn数据?

4 个答案:

答案 0 :(得分:1)

<?php
    $url = '{
  "success":true,
  "timestamp":1503291248,
  "quotes":{
    "SAD":"ABC",
    "LOVE":"XYZ",
    "FRIENDSHIP":"SOME",
    "ENMITY":"LOREM IPSUM",
    ... //indicates there are a lot more categories
  }
}';
    $content = file_get_contents($url);
    $json = json_decode($content, true);

    foreach ( $json as $idx=>$json ) {
       if(is_array($json))
       {
         foreach($json as $iidx=>$jjson) 
         {
             echo $iidx.":".$jjson;
         }
       }
       else
       {
         echo $idx.":".$json;
       }
    }

    $ins_qry = 'INSERT INTO json_table(jsonvalues) values ("'.$json.'")';
    $exec_qry = mysqli_query($link,$ins_qry);
?>

这将打印json数据。 要在mysql中保存此json数据,可以直接将$json值插入MySQL表的text列中。

答案 1 :(得分:0)

试试这个..

    $url = 'MY_URL';
    $content = file_get_contents($url);
    $json = json_decode($content, true);

    foreach ( $json as $val) {
        echo $val['success']; //same for other keys
    }

答案 2 :(得分:0)

$ json = file_get_contents('url_here');

$ obj = json_decode($ json);

echo $ obj-&gt; access_token;

答案 3 :(得分:-1)

您正在尝试使用未在代码中声明的变量。这是在PHP中迭代对象的正确语法。

<?php 
$url = 'MY_URL';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach ( $json as $key=>$value)
{
    echo $key." = ".$value;
} 
?>