PHPで簡単XPath(ATOM/RSS1.0)
XPath使うと簡単にXMLにアクセスできて非常に便利。PHP4とPHP5で使える方法をまとめておく。
PHP5
PHP5だとSimpleXMLで簡単にアクセスできる。下はATOMの場合。最初のエントリーのタイトルを取得している。
<?php $atom = simplexml_load_file($atom_path); $atom->registerXPathNamespace('feed', 'http://purl.org/atom/ns#'); $titles = $atom->xpath('//feed:entry/feed:title'); var_dump((string)$titles[0]); ?>
PHP4
PHP4だとSimpleXMLはないけど、DOM XMLでできる。下はRSS1.0の場合。最初のエントリーの日付を取得している。
<?php $xml = domxml_open_file($feed_url); $xpath = xpath_new_context($xml); xpath_register_ns($xpath, 'rss', 'http://purl.org/rss/1.0/'); xpath_register_ns($xpath, 'dc', 'http://purl.org/dc/elements/1.1/'); $dates = xpath_eval($xpath, '//rss:item/dc:date'); $text = $dates->nodeset[0]->first_child()->get_content(); var_dump($text); ?>
どちらもネームスペースを登録しないとちゃんと取得できないので注意。
特にRSSの方は色々拡張してあるので、それを登録しておく。
Normalizing Syndicated Feed Content
にはどちらでもアクセスしやすいようにまとめている。要チェック。