php - 通过 CLI 以编程方式添加 Joomla 文章

标签 php joomla command-line-interface article joomla3.4

我希望能够使用 Joomla CMS 中的 cli 功能从命令行以编程方式在 Joomla 中添加许多文章。

我基本上使用Create a Joomla! Article Programmatically但我的脚本在仅创建一篇带有错误行的文章后就关闭了

Error displaying the error page: Application Instantiation Error:Application Instantiation Error

这是我在 Joomla 的/cli 文件夹中运行的代码。

我使用的是 Joomla 3.4

<?php
const _JEXEC = 1;

if (file_exists(dirname(__DIR__) . '/defines.php'))
{
    require_once dirname(__DIR__) . '/defines.php';
}

if (!defined('_JDEFINES'))
{
    define('JPATH_BASE', dirname(__DIR__));
    require_once JPATH_BASE . '/includes/defines.php';
}

require_once JPATH_LIBRARIES . '/import.legacy.php';
require_once JPATH_LIBRARIES . '/cms.php';
require_once JPATH_CONFIGURATION . '/configuration.php';


class AddArticle extends JApplicationCli
{
    public function doExecute()
    {
        $count = 10;
        while ($count > 0) 
        {
            $count--;

            $jarticle                   = new stdClass();
            $jarticle->title            = 'New article added programmatically' . rand();

            $jarticle->introtext        = '<p>A programmatically created article</p>';

            $table = JTable::getInstance('content', 'JTable');
            $data = (array)$jarticle;

        // Bind data
            if (!$table->bind($data))
            {
                die('bind error');
                return false;
            }

        // Check the data.
            if (!$table->check())
            {
                die('check error');
                return false;
            }

        // Store the data.
            if (!$table->store())
            {
                die('store error');
                return false;
            }
    }
}
}

JApplicationCli::getInstance('AddArticle')->execute();

最佳答案

我能够找到这个问题的答案,因为它是在 github 上作为一个问题提出的,所以我在这里发布该解决方案。

https://github.com/joomla/joomla-cms/issues/7028

如果命令行应用程序使用JTable,则需要像这样注册应用程序:

class MakeSql extends JApplicationCli
{

   public function __construct() 
  {
     parent::__construct();
     JFactory::$application = $this; // this is necessary if using JTable
  }

  public function doExecute()
  {
      $db = JFactory::getDbo();
      // ... etc etc ...

我这样做了,效果很好。

关于php - 通过 CLI 以编程方式添加 Joomla 文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33202068/

相关文章:

php - 我可以使用 Swift 2 将数据输入 MySQL 数据库吗

php - 将用户数据存储在服务器上的 JSON 文件中

php - Json 导出为 Phoca 在 Joomla 3 上下载

html - 从 SQL 表中获取图像

node.js - Node 子进程生成标准输出返回为空

node.js - 如何将多个键映射到 yargs .alias 中的别名

php - Codeigniter 查询总是返回 TRUE

php - Facebook getUser 返回错误的 ID

php - joomla 中的 jquery-ias 不起作用

git - 使用 GitHub CLI 向上游提升 PR