LoginSignup
0
1

More than 5 years have passed since last update.

PHPで XMLパースの際に「@」から始まる属性を取得する

Last updated at Posted at 2017-08-11

ATOMで生成される、ブログの更新状況を PHPで取得した際、「@attributes」という属性を取得する必要がありました。まずは、XMLのパース。

    $xml = simplexml_load_file('http://example.com/atom.xml');

すると、例えばリンク先を取得するには次の属性を取得します。

$xml->entry->link->@attributes->href;

しかし、これは次のエラー

Fatal error: syntax error, unexpected '@', expecting ',' or ';' in...

これは、次のように取得すると取れるようです。

(string)$xml->entry->link['href']; // 8.12追記 コメントで教えて頂きました
(string)$xml->entry->link->attributes()->href;

普通に取得してしまうと、オブジェクトの形になってしまうので string で強引に型キャスト。これが正解なのか分かりませんが、ひとまず正常に取得できました。

0
1
2

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
0
1