我有一段XML,如下所示
firstname
middlename
lastname
demo
demo
demo
demo
NY
demo
demo
demo
demo
demo
demo
firstname
middlename
lastname
demo
demo
demo
demo
NY
demo
demo
demo
demo
demo
demo
现在,我可以使用SimpleXML获取PHP中的所有数据,除了date-first和date-last元素.我一直在使用下面列出的代码
$dateFirst = 'date-first';
$dateLast = 'date-last';
$streetNumber = 'street-number';
$streetPreDirection = 'street-pre-direction';
$streetName = 'street-name';
$streetPostDirection = 'street-post-direction';
$streetSuffix = 'street-suffix';
$unitDesignation = 'unit-designation';
$unitNumber = 'unit-number';
foreach ($reportDataXmlrecords->records->record as $currentRecord) {
echo $currentRecord->$dateFirst['month'].'/'.$currentRecord->$dateFirst['year'];
echo $currentRecord->$dateLast['month'].'/'.$currentRecord->$dateLast['year'];
echo $currentRecord->address->$streetNumber;
$currentRecord->address->$streetName; // ......and so on
}
其中$reportDataXmlrecords是来自父节点的simpleXML对象的一部分
但是前两个回显不打印任何内容,其他所有都正确打印,特别是,我无法访问其中的数据
也可以用于调试
print_r($currentRecord->$dateFirst);
它打印
SimpleXMLElement Object (
[@attributes] => Array ( [month] => 10 [year] => 1999 )
)
任何帮助将不胜感激.谢谢.
解决方法:
你的问题是你什么时候做
$currentRecord->$dateFirst['month']
PHP首先尝试将$dateFirst [‘month’]整体评估,然后再尝试将其用作属性
$dateFirst = 'date-first';
var_dump( $dateFirst['month'] ); // gives "d"
因为strings can be accessed by offset with array notation,但非整数偏移量转换为整数,并且由于将’month’强制转换为整数,因此您尝试执行$currentRecord-> d:
$xml = <<< XML
foo
XML;
$record = simplexml_load_string($xml);
$var = 'date-first';
echo $record->$var['month']; // foo
您可以使用大括号访问带连字符的属性:
$record->{'date-first'}['month'] // jan
在旁注中,当问题中显示的XML确实是您正在使用SimpleXml加载的XML时,例如当< records>是根节点,然后做
$reportDataXmlrecords->records->record
无法工作,因为$reportDataXmlrecords已经是根节点,如果要遍历其中的记录元素,则必须省略-> records.
标签:php,xml,simplexml
来源: https://codeday.me/bug/20191013/1909064.html