我刚接触使用PHP的XML。我有一个相当复杂的XML结构,并且在laravel中使用simplexml并且无法访问我需要获取的所有元素。我能够循环遍历大型XML文件,但是simpleXML每个记录返回两个对象,我似乎只能访问' header'中的元素,第一个返回的对象...
这是xml对象的一部分
SimpleXMLElement Object
(
[identifier] => RCM0635
[datestamp] => 2015-06-09
)
SimpleXMLElement Object
(
[lidoWrap] => SimpleXMLElement Object
(
[lido] => SimpleXMLElement Object
(
[lidoRecID] => RCM:1748
[descriptiveMetadata] => SimpleXMLElement Object
(
[objectClassificationWrap] => SimpleXMLElement Object
(
[objectWorkTypeWrap] => SimpleXMLElement Object
(
[objectWorkType] => SimpleXMLElement Object
(
[term] => musical instruments
)
)
[classificationWrap] => SimpleXMLElement Object
(
[classification] => Array
(
[0] => SimpleXMLElement Object
(
[term] => Cornet
)
[1] => SimpleXMLElement Object
(
[conceptID] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => SH_Class
)
)
)
)
)
)
使用下面的代码,我可以获得标题中的元素,但我无法弄清楚如何获取其他元素?
$streamer = \Prewk\XmlStringStreamer::createStringWalkerParser(public_path().'/xml/many_mimo_records.xml');
while ($node = $streamer->getNode()) {
$simpleXmlNode = simplexml_load_string($node);
echo (string)$simpleXmlNode->identifier;
echo (string)$simpleXmlNode->datestamp;
}
我非常感谢任何建议......
答案 0 :(得分:0)
我不确定我是否了解你,但主修:
while ($node = $streamer->getNode())
循环上行动,这意味着在第一次迭代后你会得到这个对象:
SimpleXMLElement Object
(
[identifier] => RCM0635
[datestamp] => 2015-06-09
)
所以第一次可以这样读:
` $ simpleXmlNode = simplexml_load_string($ node); echo(string)$ simpleXmlNode-> identifier; echo(string)$ simpleXmlNode-> datestamp;
`
但是在第二次迭代中你有:
`
SimpleXMLElement Object
(
[lidoWrap] => SimpleXMLElement Object
(
[lido] => SimpleXMLElement Object
(
[lidoRecID] => RCM:1748
[descriptiveMetadata] => SimpleXMLElement Object
(
[objectClassificationWrap] => SimpleXMLElement Object
(
[objectWorkTypeWrap] => SimpleXMLElement Object
(
[objectWorkType] => SimpleXMLElement Object
(
[term] => musical instruments
)
)
[classificationWrap] => SimpleXMLElement Object
(
[classification] => Array
(
[0] => SimpleXMLElement Object
(
[term] => Cornet
)
[1] => SimpleXMLElement Object
(
[conceptID] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => SH_Class
)
)
)
)
)
)
`
所以里面的代码错了。
我很想尝试这样的事情:`
while ($node = $streamer->getNode()) {
$simpleXmlNode = simplexml_load_string($node);
if (!empty($simpleXmlNode->identifier))
echo (string)$simpleXmlNode->identifier;
if (!empty($simpleXmlNode->datestamp))
echo (string)$simpleXmlNode->datestamp;
if (!empty($simpleXmlNode->lidoWrap)) {
$lido = $simpleXmlNode->lidoWrap->lido;
echo (string)$lido->lidoRecID;
// and so on as the recursive XML node objects
}
}
`