【问题标题】:Getting data from XML node in php [duplicate]从php中的XML节点获取数据[重复]
【发布时间】:2013-03-29 15:06:39
【问题描述】:

我正在从 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'

那么我哪里错了?

【问题讨论】:

标签: php xml simplexml


【解决方案1】:

尝试使用这个:

<person>
  <firstname>ABC</firstname>
  <lastname>XYZ</lastname>
</person>

然后:

$content = file_get_contents($url);

$xml = simplexml_load_string($content);

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

有效吗?

编辑:$xml-&gt;children() 中没有任何数据,因为你没有任何数据。尝试做这样的事情:

<person>
  <firstname>ABC</firstname>
  <lastname>XYZ</lastname>
  <other>
    <first>111</first>
    <second>222</second>
  </other>
</person>

<?php 
$content = file_get_contents("test.xml");

$xml = simplexml_load_string($content);

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

 ?>

这将呼应这个:

firstname: 
lastname: 
other: 111

我想拥有第一个节点,你可以这样做:

echo $xml->firstname

【讨论】:

  • 没有。它不是。 $child->getName 仅返回节点名称。但是 $child->firstname 或 $child->first-name 不返回节点的数据
【解决方案2】:

'-' 不允许在变量名中。 $child-&gt;first-name 被解释为$child-&gt;first minus name。您应该找到另一种获取内容的方法。

【讨论】:

    【解决方案3】:

    如前所述,您不能在变量名中使用-。不过,据我所知,您只是想打印出标签名称和值。如果是这样,你很可能是这样的:

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

    【讨论】:

    • 是的,当然。我正在尝试打印标签值。它确实奏效了。谢谢
    • @juco:请评论并链接到这些常见问题的现有答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多