カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

PHPでXMLファイルの解析

この記事は最終更新日から1年以上経過しています。

まずはXMLのサンプル

<?xml version="1.0" encoding="UTF-8" ?>
<rdf:RDF
  xmlns="http://purl.org/rss/1.0/"
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:admin="http://webns.net/mvcb/"
  xml:lang="ja">
  <channel rdf:about="http://www.example.jp/test.rdf">
    <title>title</title>
    <link>http://www.example.jp/</link>
    <dc:date>2006-07-06T20:14:34+09:00</dc:date>
    <description>description</description>
    <admin:generatorAgent rdf:resource="http://www.infomaker.jp/editorlite/?v=0.92b" />
    <items>
      <rdf:Seq>
        <rdf:li rdf:resource="http://www.example.jp/#he20060706"/>
      </rdf:Seq>
    </items>
  </channel>

  <item rdf:about="http://www.example.jp/#he20060706">
    <title>test</title>
    <link>http://www.example.jp/</link>
    <dc:date>2006-07-06</dc:date>
    <description>description</description>
  </item>

</rdf:RDF>

PHPで解析します。

// XMLファイルを読み込みインスタンスを生成
$xml = simplexml_load_file("ファイルのパス");
//$xml = new SimpleXMLElement("ファイルのパス", null, true); // この書き方でも可

// channel要素がある場合
//$channel = $xml->channel;
// 下のforeach取り出し元配列を$channel->itemに変更

foreach($xml->item as $item) {

    // 各内容を変数に格納
    //{
        $url         = $item->link;
        $title       = $item->title;
        $description = $item->description;

        // Namespace付の子要素を取得
        //{
            // childrenメソッドにて取得(引数のURLはxmlns:dc=[URL]から取得)
            $dc = $item->children('http://purl.org/dc/elements/1.1/');

            $date = date("Y-m-d", strtotime($dc->date));
        //}
    //}

}

dcとは?

Dublin Coreの略。
Dublin Coreモジュールとは、標準的なメタデータ記述要素として用いられるDublin CoreのDCMESを利用するモジュールです。

この記事がお役に立ちましたらシェアお願いします
2,177 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です