【发布时间】:2021-05-01 00:36:08
【问题描述】:
我的代码解析一个数组以获取 xml 文件中各种属性的路径。我将 xml 作为 simplexmlelement 加载,如下所示:
$xml = simplexml_load_string($xml_string);
$address = $xml->response->addressinformation->records->record[0];
此代码将起作用并显示正确的 '03' 值:
$from = $address->{'from-date'}['month'];
echo $from;
//prints '03'
from-date 周围的 {} 是必需的,因为元素名称中包含 -。
下面的代码块看起来应该在功能上等同于上面的代码,但是当我将路径分配给 $variable 时它不起作用。
$path = "{'from-date'}['month']";
$from = $address->$path;
echo $from;
//prints ''
$path = "from-date['month']";
$from = $address->$path;
echo $from;
//prints ''
此代码将起作用。
//normal path
$from = $address->{'from-date'};
//path assigned to variable
$path = "from-date";
$from2 = $address->$path;
var_dump($from);
var_dump($from2);
//both correctly output - object(SimpleXMLElement)#1587 (1)
//{ ["@attributes"]=> array(2) { ["year"]=> string(4) "2003" ["month"]=> string(2) "03" } }
只有当我使用['month'] 定位特定属性时,它似乎才会失败。我知道这个问题的答案只是我做错了一些愚蠢的事情。谁能告诉我这是什么?
示例 XML
$xml_string = '
<?xml version="1.0" encoding="utf-8"?>
<root>
<response>
<addressinformation>
<records>
<record id="1">
<fullname>JOHN E DOE</fullname>
<firstname>JOHN</firstname>
<middlename>E</middlename>
<lastname>DOE</lastname>
<fulldob>01/01/1970</fulldob>
<from-date year="2003" month="03"/>
<to-date year="2010" month="09"/>
</record>
<record id="2">
<fullname>JOHN E DOE</fullname>
<firstname>JOHN</firstname>
<from-date year="2003" month="03"/>
<to-date year="2010" month="09"/>
</record>
</records>
</addressinformation>
<otherinformation>
<records>
<record id="3">
<fullname>JOHN DOE</fullname>
<firstname>JOHN</firstname>
<lastname>DOE</lastname>
<fulldob>01/01/1970</fulldob>
</record>
<record id="4">
<fullname>JOHN EDWARD DOE</fullname>
<firstname>JOHN</firstname>
<middlename>EDWARD</middlename>
<lastname>DOE</lastname>
<fulldob>19700000</fulldob>
</record>
<record id="5">
<fullname>JOHN EDWARD DOE</fullname>
<firstname>JOHN</firstname>
<middlename>EDWARD</middlename>
<lastname>DOE</lastname>
<fulldob>19830000</fulldob>
</record>
</records>
</otherinformation>
</response>
</root>
';
【问题讨论】: