1

URL から XML データを取得しており、特定のノードからデータを抽出したいと考えています。

ここに私のXMLデータがあります

<person>
  <first-name>ABC</first-name>
  <last-name>XYZ</last-name>
</person>

これが私のPHPコードです:

$content = file_get_contents($url);

$xml = simplexml_load_string($content);

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child->first-name . "<br>";
  }

PHP は次のエラーを返します。

Use of undefined constant name - assumed 'name'

それで、どこが間違っているのですか?

4

3 に答える 3

0

'-'を変数名に使用することはできません。$child->first-nameと解釈され$child->first minus nameます。コンテンツを取得する別の方法を見つける必要があります。

于 2013-04-07T15:04:17.823 に答える
0

As already mentioned, you cannot use - in the variable name. From what I can gather though, you are simply trying to print out the tag name and value. If so, you're probably after this:

foreach($xml->children() as $child)
{
    echo "{$child->getName()}: $child <br />";
}
于 2013-04-07T15:07:51.290 に答える