3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * @package Joomla.Cli * * @copyright (C) 2012 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * A command line cron job to bulk import JSON data into Joomla articles */ // Initialize Joomla framework const _JEXEC = 1; // Load system defines if (file_exists(__DIR__ . '/defines.php')) { require_once __DIR__ . '/defines.php'; } if (!defined('_JDEFINES')) { define('JPATH_BASE', __DIR__); require_once JPATH_BASE . '/includes/defines.php'; } // Get the framework. require_once JPATH_LIBRARIES . '/import.legacy.php'; // Bootstrap the CMS libraries. require_once JPATH_LIBRARIES . '/cms.php'; class BulkArticles extends JApplicationCli { public function doExecute(): void { $this->out(JText::_('Start')); // Fetch the JSON data and Run the insertArticle bulk data import to articles function $curlOpts = [ CURLOPT_URL => 'https://api.dtn.com/publishing/news/articles?categoryId=16%2C17%2C18&limit=10&maxAge=30&apikey=placeholder', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', ]; try { $fetchedArticles = $this->curlToObject($curlOpts); if ($fetchedArticles) { $this->out(JText::_('Fetched Articles: ' . count($fetchedArticles))); } $insertedIds = $this->insertArticles($fetchedArticles); if ($insertedIds) { $this->out(JText::_('Inserted IDs: ' . implode(', ', $insertedIds))); } } catch (exception $e) { $this->out(JText::_($e->getMessage())); } $this->out(JText::_('Complete')); } /** * @throws Exception */ private function curlToObject(array $curlOpts): array { $ch = curl_init(); curl_setopt_array($ch, $curlOpts); $result = curl_exec($ch); $error = curl_error($ch); // Get the last error curl_close($ch); if ($error) { throw new Exception($error); } return json_decode($result); } /** * @throws Exception */ private function insertArticles(array $articles): array { require_once JPATH_ADMINISTRATOR . '/components/com_content/models/article.php'; $articleModel = new ContentModelArticle([]); foreach ($articles as $article) { $articleData = [ 'id' => 0, 'catid' => 8, 'title' => ucwords(strtolower($article->title)), 'alias' => JFilterOutput::stringURLSafe($article->title), 'introtext' => strip_tags($article->storySummary), 'fulltext' => strip_tags($article->content), 'state' => 1, 'access' => 2, 'created_by' => 332, 'language' => '*', 'rules' => [ 'core.edit.delete' => [], 'core.edit.edit' => [], 'core.edit.state' => [] ], ]; if (!$articleModel->save($articleData)) { throw new Exception($articleModel->getError()); } else { $newIds[] = $articleModel->getItem()->id; } } return $newIds ?? []; } } JApplicationCli::getInstance('BulkArticles')->execute();

preferences:
17.82 ms | 402 KiB | 5 Q