cURL检索json数据并从url存储在mysql数据库中 [英] cURL retrieve json data and store in mysql database from url

查看:91
本文介绍了cURL检索json数据并从url存储在mysql数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 cURL 中遇到问题。在这里,我可以从另一个源代码获取json数据,我也有一些想法。但实际上我无法将json数据保存到自己的sql数据库服务器中。我想从

i'm facing problems into cURL. here i can get the json data from another source code and also i got some ideas. but really i can't save the json data into my own server in sql database. i wanna to retrieve the data from


url中检索数据: https://jamuna.tv/wp-json/wp/v2/posts

,并希望保存到我的服务器(mysql)中。

and wanna to save into my server (mysql).

这是我要保存在mysql服务器中的$ url json数据:

here is the $url json data i wanna to save in mysql server:

id
date
link
title
content
author
categories
wp:attachment

,我想将它们保存到mysql数据库中。我的表格名称是新闻并且我想将它们保存到我的表列中。

and i want to save them into mysql database. my table name is "news" and i want to save them into my table columns.

id [id]
title [title]
description [content]
date [date]
category [categories]
thumbnail [wp:attachment]
admin [author]

在这里,我从url标记json并替换为我的sql列名称。如果有人能给我说明我如何从用户那里获取数据并保存到mysql中。

here i'm mark the json from url and replaced into my sql columns name. if anyone can give me the instructions about how i can fetch the data from user and save into mysql.

感谢前进。

推荐答案

PHP提供了所需的实现。您必须检查值是否有效,或者数组成员是否存在。这只是示例的原始实现。

There is an implementation of your desired with PHP. You must check if values are valid or not or if the array members exist or not. This is just a primitive implementation of your example.

<!DOCTYPE html>
<html>
<body>

<?php

// db connection
$options = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);

$db = new PDO('mysql:host=localhost;dbname=test;', 'user', 'pass', $options);

// download json from url
$json = file_get_contents('https://jamuna.tv/wp-json/wp/v2/posts');

echo '<br/>';

$sql = "INSERT INTO `mytable` (`id`,`title`,`description`,`date`,`category`,`thumbnail`,`admin`)
                      VALUES (:id, :title, :content , :date, :categories, :attachment, :author)";
$stm = $db->prepare($sql);

// parse JSON
$arr = json_decode($json, true);
$i = 0;

foreach ($arr as $record) {

    echo "==================Insert record " . $i ++ . "<br>";

    $data = array(
        ':id' => $record['id'],
        ':title' => $record['title']['rendered'],
        ':content' => $record['content']['rendered'],
        ':date' => $record['date'],
        ':categories' => $record['categories'][0],
        ':attachment' => $record['_links']['wp:attachment'][0]['href'],
        ':author' => $record['author']
    );

    var_dump($data);
    // inserting a record
    $stm->execute($data);
}
?>

</body>
</html>

这篇关于cURL检索json数据并从url存储在mysql数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆