LoginSignup
6
7

More than 5 years have passed since last update.

PHPでRSSを作成

Posted at

rdf拡張子のRSSを表示させる場合は以下の行が書かれた「.htaccess」を作成して、表示させたいrdfのディレクトリに置いてください。
「.htaccess」を作成させる場合はサーバーにアップしてからリネームすると「.」がついたファイルを作成できます。

.htaccess
AddType application/xml .rdf

SimpleXMLElementを使う事で、簡単にRSSを作成できます。
今回は作成したRSSをすぐに表示させていますが、一度ファイルとして保存したものを表示する方法でもいいと思います。
表示されない場合はhtmlspecialchars()で文字をエスケープしてから表示してみてください。
myblog.rdfを保存する場合は、サーバーの公開ディレクトリ直下にrssフォルダを作成してください。

rss.php
<?php

    try{

        $RSS = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
    <rss version="2.0">
        <channel>
            <language>ja</language>
        </channel>
    </rss>
EOT;

        $rssFileName = 'myblog.rdf';

        $XML = new SimpleXMLElement($RSS);
        $XML->channel->addChild('title', "ブログタイトル!");
        $XML->channel->addChild('link', 'http://' . $_SERVER['HTTP_HOST'] . '/rss/' . $rssFileName);
        $XML->channel->addChild('description', "ブログの更新情報です");

        $item = $XML->channel->addChild('item');
        $item->addChild('title', "記事タイトル");
        $item->addChild('link', 'http://' . $_SERVER['HTTP_HOST'] . "/page/mypage.html");
        $item->addChild('category', "カテゴリ");
        $item->addChild('description', "記事についての説明");
        $item->addChild('content', "記事の中身");
        $item->addChild('date', date('Y-m-d H:i:s'));


        header('Content-Type: text/xml');
        ob_end_clean();
        echo $XML->asXML();

        $file = fopen($_SERVER['DOCUMENT_ROOT'] . '/rss/' . $rssFileName, "w");
        fwrite($file, $XML->asXML());
        fclose($file);

    }catch ( Exception $e ) {
    }


?>

ポイントとしてはob_end_cleanを使用することで、作成したRSSを直接表示させることが出来ます。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7