LoginSignup
1

simplexml_load_fileで要素名にハイフンがついていると読み込めない

Last updated at Posted at 2024-03-09

simplexml_load_fileで要素名にハイフンがついていると読み込めず、「Parse error: syntax error, unexpected ‘[‘」エラーが発生する場合の対処方法です。

※ これは2016-10-25に個人ブログで公開した記事を移植し、CC0-1.0で提供しています。情報は古い可能性があります。

現象

simplexml_load_fileで取得できなかったUser-Agents.orgのxmlは次のとおりになっていました(抜粋)。

<user-agents>
  <user-agent>
    <String></String>
  </user-agent>
</user-agents>

次のPHPコードを実行するとエラーが発生しました。

<?php
$xml=simplexml_load_file("http://www.user-agents.org/allagents.xml");
print($xml->user-agent[0]->String);
?>
Parse error: syntax error, unexpected ‘[‘ in test.php on line 3

原因

メンバ変数名に特殊文字が入っているため発生します。

対処方法

次のように変更しました。

$xml->user-agent[0]->String;

$xml->{'user-agent'}[0]->String;

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
1