php simplexml 值,使用php simplexml从XML显示数据

我有一段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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值