LoginSignup
6
7

More than 5 years have passed since last update.

SimpleXMLのデータはvar_dumpで見えない! (こともある)

Last updated at Posted at 2012-04-26

SimpleXMLでATOMをパースしようとして、ちょっと手こずったのでメモ。(PHPでXML扱うのが久しぶり)

  • SimpleXMLのデータはvar_dumpなどで、見えないことがある。(←重要)
  • foreach じゃないと言うことを聞かないかも。
  • 解析したデータを使いたい場合、文字列にキャストすること。
<?php
//フィードを解析して、記事データを取得する関数
function get_articles($url, $max = 5){
    $atom = simplexml_load_file($url);
    $articles = array();
    $n = 0;
    foreach ($atom->entry as $item){
        $attr = $item->link->attributes();
        $articles[] = array(
            'title' => (string)$item->title,
            'url' => (string)$attr['href'],
            'date' => (string)$item->published,
        );
        if ($max <= ++$n) break;
    }
    return $articles;
}

//使用例 : JSONで出力
$feed_url = 'http://somewhere/atom.xml';//フィードのURL
$articles = get_articles($feed_url);//記事データを取得
header('Cache-Control: public,max-age=3600');
echo json_encode($articles);

おまけ

PHPの命名規則から逸脱するプロパティ名は、

$xml->{'sample-prop'}

のようにすればOK。

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