我遇到了这样一个问题,即我的xml文件的某些节点已解析& ;;在未检测到其他人的情况下正确显示(至少我不知道这里出了什么问题)
我将提供link to it而不是发布xml文件.这是一个小的XML代码段供您查看xml结构:
World of Warcraft EU Pre-Paid Game Time Card 60 Days
EUR
现在,我正在使用此代码来解析/读取xml文件.
$xmlDOM = new DOMDocument();
$xmlDOM->load("http://inexus.us/compare.xml");
$document = $xmlDOM->documentElement;
foreach ($document->childNodes as $node) {
if ($node->hasChildNodes()) {
foreach($node->childNodes as $temp) {
echo $temp->nodeName."=".$temp->nodeValue."
";
}
}
}
使用该代码,我得到每个元件的名称
但是我还需要获取存储在o元素中的信息…(即id,url,price),但我不太了解如何访问它们.
输出也会返回几个#text =块. (我想这是由于xml中的空格引起的吗?)
输出的一小段代码:
#text=
#text=
o= World of Warcraft EU Pre-Paid Game Time Card 60 Days EUR
#text=
o= World of Warcraft EU Battle Chest cd-key EUR
#text=
o= World of Warcraft EU Cataclysm cd-key EUR
#text=
任何帮助/提示表示赞赏!
解决方法:
对于这样的XML文档,在SimpleXML中处理起来通常更容易.通常,您要查找的称为属性.在作为元素子元素的文本值旁边,元素还具有属性.
在SimpleXML中,访问非常简单:使用数组符号和字符串键访问元素的属性:
$game['id']; # id attribute of $game (here the element)
要访问一个孩子(通常只有一个孩子,例如< name>),可以通过其child-element-name来访问它:
$game->name; # (first) name child element of $game
并且如果您在字符串上下文中使用它(例如,作为字符串参数; echo或强制转换(字符串)$game->名称),它将返回的不是元素,而是内部的文本值.
这是一些示例代码(也使用简单的xpath):
$url = 'http://inexus.us/compare.xml';
$xml = simplexml_load_file($url);
foreach($xml->xpath('/*/group/o') as $index => $game)
{
printf("[%04d] %' -48s %' 5s %s\n \n",
$game['id'], # id attribute
trim($game->name), # name child text value
$game['price'], # price attribute
trim($game->currency), # currency child text value
$game['url'] # url attribute
);
}
这是输出:
[0001] World of Warcraft EU Pre-Paid Game Time Card 60 Days 21.43 EUR
[0003] World of Warcraft EU Battle Chest cd-key 10.31 EUR
[0668] World of Warcraft EU Cataclysm cd-key 6.18 EUR
[0954] World of Warcraft EU Mists of Pandaria cd-key 18.80 EUR
[0988] World of Warcraft EU Battle Chest + Cataclysm cd-key 15.48 EUR
[0018] Eve Online Pre-Paid Card 60 Days Special Edition 28.40 EUR
[0766] Eve Online +30 Days cd-key 11.60 EUR
[1057] Eve Online Pre-Paid Card 60 Days 25.82 EUR
[0029] Sony Online Pre-Paid 30 days EU 14.19 EUR
...
标签:dom,xml,parsing,php
来源: https://codeday.me/bug/20191031/1973633.html