我正在从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'
我哪里错了?
如前所述,不能在变量名中使用-
。从我收集到的信息来看,您只是试图打印出标记名称和值。如果是这样,你可能在后面:
foreach($xml->children() as $child)
{
echo "{$child->getName()}: $child <br />";
}
不允许在变量名中使用'-'
。$child->first-name
被解释为$child->first minus name
。
试着用这个:
<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>";
}
it works ?
编辑:你不会有任何数据在$xml->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>";
}
?>
this将回显this:
firstname:
lastname:
other: 111
如果您想拥有第一个节点,您可以简单地执行:
echo $xml->firstname