织梦cms栏目跨站调用

跨站调用概述

织梦CMS的跨站调用是指A织梦网站调用B织梦网站栏目下的文章数据。这在站群管理、主站聚合子站内容等场景中非常实用。实现方式主要有JSON接口调用、数据库直连和RSS订阅三种。

一、通过JSON接口跨站调用

1.1 在被调用站创建JSON接口

在目标站的根目录创建 api/json_article.php

<?php
require_once(dirname(__FILE__)."/include/common.inc.php");
header('Content-Type: application/json; charset=utf-8');

$typeid=isset($_GET['typeid']) ? intval($_GET['typeid']) : 0;
$row=isset($_GET['row']) ? intval($_GET['row']) : 10;

$sql="SELECT id,title,description,litpic,pubdate 
        FROM dede_archives WHERE typeid={$typeid} AND arcrank=0 
        ORDER BY pubdate DESC LIMIT {$row}";
$dsql->SetQuery($sql);
$dsql->Execute();

$data=array();
while($rs=$dsql->GetArray()){
    $data[]=array(
        'id'=> $rs['id'],
        'title'=> $rs['title'],
        'desc'=> mb_substr(strip_tags($rs['description']), 0, 100),
        'thumbnail'=> $rs['litpic'],
        'url'=> '/plus/view.php?aid='.$rs['id'],
        'date'=> date('Y-m-d', $rs['pubdate'])
    );
}
echo json_encode(array('code'=>200, 'data'=>$data), JSON_UNESCAPED_UNICODE);
?>

1.2 在调用站中使用JSON数据

<!-- 通过PHP获取并展示 -->
{dede:php}
$api_url='http://子站点域名/api/json_article.php?typeid=3&row=10';
$json=file_get_contents($api_url);
$result=json_decode($json, true);
if($result['code']==200){
    foreach($result['data'] as $item){
        echo '<li>';
        echo '<a href="'.$item['url'].'">'.$item['title'].'</a>';
        echo '<span>'.$item['date'].'</span>';
        echo '</li>';
    }
}
{/dede:php}

二、通过数据库直连跨站调用

如果A站和B站在同一服务器或网络互通:

<?php
// 建立到B站的数据库连接
$conn_b=mysqli_connect('B站数据库IP', '用户名', '密码', 'B站数据库名');
mysqli_set_charset($conn_b, 'utf8');

$sql="SELECT a.id,a.title,a.pubdate,t.typename 
        FROM dede_archives a 
        LEFT JOIN dede_arctype t ON a.typeid=t.id 
        WHERE a.typeid=3 AND a.arcrank=0 
        ORDER BY a.pubdate DESC LIMIT 10";
$result=mysqli_query($conn_b, $sql);

while($row=mysqli_fetch_assoc($result)){
    echo '<li><a href="http://B站域名/plus/view.php?aid='.$row['id'].'">';
    echo $row['title'].'</a></li>';
}
mysqli_close($conn_b);
?>

三、使用织梦的多站点功能

织梦CMS V5.7 SP1+ 版本支持内置的多站点管理:

  1. 进入 系统 > 多站点管理
  2. 添加子站点信息(域名、站点根目录等)
  3. 在模板中使用多站点标签调用子站内容

四、通过RSS订阅实现跨站调用

利用织梦的RSS功能获取栏目内容:

<?php
// 读取子站的RSS订阅
$rss_url='http://子站域名/plus/rss.php?tid=3';
$rss=simplexml_load_file($rss_url);

foreach($rss->channel->item as $item){
    $title=(string)$item->title;
    $link=(string)$item->link;
    $date=(string)$item->pubDate;
    echo "<li><a href='{$link}'>{$title}</a></li>";
}
?>

五、跨域调用注意事项

推荐方案:对于站群管理,推荐使用JSON接口+本地缓存的方式。在A站请求B站数据后缓存到本地文件(如缓存1小时),这样可以大幅提升页面加载速度并减少对B站服务器的压力。