search
HomeBackend DevelopmentPHP TutorialWordPress 跨域请求 JSON 并保存在本地

我在给一个 WordPress 主题添加一个功能:在首页显示当地的 PM2.5 指数。使用了这个第三方服务.

GET 方法可以直接请求到 JSON ,但是 请求次数有限制 (比如一小时最多 5 次),所以我想用 PHP 请求到我要的 JSON,然后保存在服务器上,这样用户访问页面时,直接从我的服务器上请求数据即可。

现在我有这两种思路:

  • 我一开始的思路是,用 PHP 请求到 JSON 后,把 JSON 文件保存到 wp-content/uploads 目录(想法类似于上传文件),找到了 wp_handle_upload 这个函数(和一些零散的资料Link 1, Link 2),但是一直没弄明白怎么用,希望有用过的朋友能指点一下。

  • 后来又想到一个办法,在主题目录里面预先放一个 JSON 文件,然后用 PHP 请求第三方的数据之后再复写这个 JSON 文件。我想这样就避开了 “ 上传 ” 这个动作,直接操作一个 JSON 文件即可。

请问上面那一种方式更可行?如果可行,具体需要用到哪些技术?我后端知识浅薄,希望大家不吝赐教,先多谢了!

回复内容:

我在给一个 WordPress 主题添加一个功能:在首页显示当地的 PM2.5 指数。使用了这个第三方服务.

GET 方法可以直接请求到 JSON ,但是 请求次数有限制 (比如一小时最多 5 次),所以我想用 PHP 请求到我要的 JSON,然后保存在服务器上,这样用户访问页面时,直接从我的服务器上请求数据即可。

现在我有这两种思路:

  • 我一开始的思路是,用 PHP 请求到 JSON 后,把 JSON 文件保存到 wp-content/uploads 目录(想法类似于上传文件),找到了 wp_handle_upload 这个函数(和一些零散的资料Link 1, Link 2),但是一直没弄明白怎么用,希望有用过的朋友能指点一下。

  • 后来又想到一个办法,在主题目录里面预先放一个 JSON 文件,然后用 PHP 请求第三方的数据之后再复写这个 JSON 文件。我想这样就避开了 “ 上传 ” 这个动作,直接操作一个 JSON 文件即可。

请问上面那一种方式更可行?如果可行,具体需要用到哪些技术?我后端知识浅薄,希望大家不吝赐教,先多谢了!

就一个小功能而已,不和WordPress扯上关系也完全么问题呀。直接写一个PHP文件,将抓取过来的JSON文件放到wp-content/uploads目录内,如果文件存在,则直接读取,不存在则进行抓取工作。文件的文件名可以采用“时间地点”的格式。至于主题里头直接就用file_get_contents获取就OK了。给个示例代码:

<code><?php $name = "20140129Beijing";
    $file = './wp-content/uploads/'.$name.'.json';
    $api_url = "";
    if(file_exist($file)) {
        echo file_get_contents($file);
    } else {
        $json = file_get_contents($api_url);
        file_put_contents($json, $file);
        echo $json;
    }
?>
</code>

用用WordPress的API,也是个好选择。再不济WordPress也是个封装了很多东西的框架嘛。

WordPress插件(或主题)如果想存储少量数据,也不必用文件这么麻烦,大可直接借助WordPress的选项系统,把数据扔进wp_options表中。就像这样:

<code><?php $pm25_mod_data = get_option('pm25_mod_data_cache');
if (!$pm25_mod_data) {
    $pm25_mod_data = file_get_contents($pm25_mod_apiurl); //这里也可以调用你做API请求的任何有效代码或函数调用
    add_option('pm25_mod_data_cache', $pm25_mod_data);
}
echo $pm25_mod_data; //或任何其他的格式化输出
?>
</code>

以上这段代码只能实现访客首次访问,且由于种种原因没有缓存时不出错。

你还需要有一个定时刷新,强行更新缓存内容的机制。

这个你应该查查WordPress Cron - WordPress封装了一个环境无关的计划任务系统,既能在可以使用真实cron的平台工作,也可以在没有计划任务程序的情况下“变通的”工作。用这个来定时取最新数据很适合。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version