【发布时间】:2020-12-07 09:09:14
【问题描述】:
我有一个网站以这种格式返回 json:domain.tld/json/1/、domain.tld/json/2/、domain.tld/json/3/、domain.tld/json/4/ , domain.tld/json/5/ 等
我知道每天 json 的数量,假设今天我有 5 个。我想将数字 5 放入我的字段并按 get all。该脚本应该遍历所有页面并将它们插入我的第二个网站,但现在它只插入一页,我不明白为什么。对不起我的英语不好,我不是本地人。这是我的代码:
<?php
function request($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_REFERER, "https://domain.tld");
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$count_pages = $_POST["count_pages"];
if(isset($_POST["get_all"])) {
for ($i = 0; $i < $count_pages; $i++) {
$page_number = $i + 1;
$data = request("https://mypage.tld/$page_number/");
$json_data = trim($data);
$json_data = json_decode($data, true);
$post_title = $json_data["post_title"];
$post_content = $json_data["post_content"];
$insert_post = wp_insert_post([
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
'post_type' => 'news',
]);
}
}
?>
<form action="" method="post">
<input type="text" name="count_pages" placeholder="Number of pages" style="width:500px;">
<input type="submit" value="Get all" name="get_all">
</form>
【问题讨论】:
-
在这一行:" request("mypage.tld/$page_number/"); " $page_number 应该做什么? $page_number 将是一个数字,比如 '1' 所以 URL 将是 'mypage.tld/1' 这就是你想要的吗?假设返回你的变量 $data 是什么?
-
有了这个 $data = request("mypage.tld/$page_number/"); $data 假设成为一个 wp 对象,其中包含页面详细信息,但前提是 request() 函数返回了一些数据。跨度>
-
它应该返回一个带有 post_title、post_content 的数组。每个页面都有不同的数组,内容不同。每次脚本运行时,$page_number 都应该是 +1。例如,它以 mydomain.tld/1/ 开头。下一次运行应该是 mydomain.tld/2/ 等,直到 5 页的循环完成。所有 5 个页面都有数据。
-
我已经测试了你的函数:函数 request($url) 它返回页面的源代码以及你放置的 URL,在你的例子中,你的 URL 将采用这种形式 '@987654324 @' 这个 URL 即使页面存在这个 URL 也不会返回一个数组。它是一个简单的 CURL 函数,并且您使用的是一个公共 URL,当您在浏览器中访问该页面时,它将返回一个正常的响应。跨度>
-
我正在为你准备代码。