Nasser Mansouri
Nasser Mansouri

Reputation: 750

get joomla articles in json or XML format using rest api

I have a mobile app (Cordova HTML mobile app in fact) and one customer web application (php) and one main joomla based website. this jooma site is base for my system and I want to show its blog posts in mobile app (using JavaScript) and also in my web app.

I can use RSS feed for displaying HEADLINEs but it is limited (some how). I know php and a little about creating simple component/module for joomla. know I think how I can get articles from dB in right way?

blog posts are public and I need to know how I must get articles from database or is there any extension for it?

also I need to order article by hits and published date.

Upvotes: 3

Views: 2177

Answers (1)

Abhinav Verma
Abhinav Verma

Reputation: 435

I have created a similar kind of script for my own joomla site where i fetch articles between 2 date ranges.

My solution approach is to initialize joomla framework outside joomla in a custom php file which stays in root of joomla folder.

i named my file as articleApi.php and kept at root of joomla (assuming your joomla is 3.5.x or greater)

here is my script :

i used epoch timestamp to fetch articles between 2 dates the url should be : http://YOUR_JOOMLA_SITE.COM/articleApi.php?starttime=1503260194&endtime=1503519394

<?php
define( '_JEXEC', 1 ); //This will define the _JEXEC constant that will allow you to access the rest of the Joomla framework
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once ( JPATH_BASE . '/includes/defines.php' );
require_once ( JPATH_BASE . '/includes/framework.php' );
require_once ( JPATH_BASE . '/libraries/joomla/factory.php' );
require_once ( JPATH_BASE . '/components/com_content/helpers/route.php');

// Instantiate the application.
$app = JFactory::getApplication('site');
// Initialise the application.
$app->initialise();
// Now you can use all classes of Joomla
$db = JFactory::getDBO();
$doc = JFactory::getDocument();
jimport( 'joomla.application.module.helper' );
jimport( 'joomla.application.component.model' );
jimport( 'joomla.application.router' );
JModelLegacy::addIncludePath(JPATH_SITE.'/components/com_content/models');
$tags = new JHelperTags;

function isTimestamp($timestamp) {
    if(ctype_digit($timestamp) && strtotime(date('Y-m-d H:i:s',$timestamp)) === (int)$timestamp) {
        return true;
    }else{
        return false;
    }
}

$jinput = JFactory::getApplication()->input;
$rawStartDate = $jinput->get('starttime', null, 'int');
$rawEndDate = $jinput->get('endtime', null, 'int');
$startDate = JFactory::getDate($rawStartDate);
$endDate = JFactory::getDate($rawEndDate);

$dateDiff = date_diff($startDate,$endDate);



if(!isTimestamp($rawStartDate)){
    $error = new stdClass();
    $error->status=406;
    $error->name='Start Date/time Range is incorrect.';
    header('content-type: application/json; charset=utf-8');
    header("access-control-allow-origin: *");
    header('Content-Type: application/json');
    header("HTTP/1.1 406");
    echo(json_encode($error));
    jexit();
}

if(!isTimestamp($rawEndDate)){
    $error = new stdClass();
    $error->status=406;
    $error->name='End Date/time Range is incorrect.';
    header('content-type: application/json; charset=utf-8');
    header("access-control-allow-origin: *");
    header('Content-Type: application/json');
    header("HTTP/1.1 406 Not Acceptable");
    echo(json_encode($error));
    jexit();
}

if($rawStartDate > $rawEndDate){
    $error = new stdClass();
    $error->status=406;
    $error->name='start Date/time is greater than end date/time.';
    header('content-type: application/json; charset=utf-8');
    header("access-control-allow-origin: *");
    header('Content-Type: application/json');
    header("HTTP/1.1 406 Not Acceptable");
    echo(json_encode($error));
    jexit();
}


if($dateDiff->m > 1){
    $error = new stdClass();
    $error->status=406;
    $error->name="Range shoudn't be more than one month";
    header('content-type: application/json; charset=utf-8');
    header("access-control-allow-origin: *");
    header('Content-Type: application/json');
    header("HTTP/1.1 406");
    echo(json_encode($error));
    jexit();
}

$articles = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$i=0;
$output = [];
$ArticleFinal = array();
$appParams = JFactory::getApplication()->getParams();
$articles->setState('params', $appParams);
$articles->setState('filter.published', 1);
$articles->setState('filter.date_filtering','range');
$articles->setState('filter.start_date_range',$startDate);
$articles->setState('filter.end_date_range',$endDate);
$articles->setState('filter.ordering','a.created');
$items   = $articles->getItems();

foreach ($items as $key => $item)
{
    /*echo "<pre>";
    print_r($item);
    echo "</pre>";*/
    $tags->getItemTags('com_content.article', $item->id);
    $item->category_title = $item->category_title;
    $item->slug     = $item->id . ':' . $item->alias;
    $item->catslug  = $item->catid . ':' . $item->category_alias;
    $item->link     = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catid, $item->language));
    //jexit($item->link);
    $ArticleFinal[$i]["articleId"]                  = $item->id;
    $ArticleFinal[$i]["title"]                      = $item->title;
    $ArticleFinal[$i]["ArticleUrl"]                 = JURI::root() . JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catid, $item->language));
    $ArticleFinal[$i]["text"]                       = $item->introtext . $item->fulltext;
    $ArticleFinal[$i]["categoryName"]               = $item->category_title;
    $ArticleFinal[$i]["categoryUrl"]                = JURI::root() . JRoute::_(ContentHelperRoute::getCategoryRoute($item->catid));
    $ArticleFinal[$i]["createdDate"]                = $item->created;
    $ArticleFinal[$i]["modifiedDate"]               = $item->modified;
    $ArticleFinal[$i]["createdBy"]                  = JFactory::getUser($item->created_by)->name;
    $ArticleFinal[$i]["createdByEmail"]             = JFactory::getUser($item->created_by)->email;
    $ArticleFinal[$i]["modifiedBy"]                 = JFactory::getUser($item->modified_by)->name;
    $ArticleFinal[$i]["modifiedByEmail"]            = JFactory::getUser($item->modified_by)->email;
    foreach($tags->itemTags as $keyTags => $valueTags){
        $ArticleFinal[$i]["tags"][$keyTags]["tag".$keyTags]         = $valueTags->title;
        $ArticleFinal[$i]["tags"][$keyTags]["tag".$keyTags."_url"]  = JURI::root() . 'tag/'.$valueTags->tag_id.'-'.$valueTags->alias;
    }

    $image = json_decode($item->images);
    if($image->image_intro){
        $ArticleFinal[$i]["storyImages"]["imageUrl"] = JURI::root() . $image->image_intro;
    }else{
        $ArticleFinal[$i]["storyImages"]["imageUrl"] = JURI::root() . $image->image_fulltext;
    }
    $i++;
}

$output[0]["articles"] = $ArticleFinal;
$output[0]["count"] = $i;

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
header('Content-Type: application/json');
echo(json_encode($output));
?>

i Hope this works for you, you can even use my approach to get your customised solution. Happy coding !

Upvotes: 2

Related Questions