【发布时间】:2017-10-20 13:07:26
【问题描述】:
XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd country="USA">
<disk>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<price>10.90</price>
</disk>
<disk>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<price>9.90</price>
</disk>
<disk>
<title>KDGFJDLF</title>
<artist>mnxc lxck</artist>
<price>7.20</price>
</disk>
</cd>
<cd country="USA">
<disk>
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<price>12.90</price>
</disk>
<disk>
<title>ASD</title>
<artist>abc def</artist>
<price>12.30</price>
</disk>
</cd>
</catalog>
我需要获取每张 cd 的最后一个孩子和倒数第二个孩子(价格)。
所以第一张 CD 的结果是: 最后一个孩子(磁盘 3):7.20 &倒数第二个孩子(磁盘 2):9.90
第二张CD的结果是: 最后一个孩子(磁盘 2):12.30 &倒数第二个孩子(磁盘 1):12.90
只需要价格
我可以知道其中一张 cd 的价格,但我无法获得每张 cd 的价格(如果添加了新的)。
<?php
$xml = new DOMDocument();
$xml->load(realpath('cd.xml'));
$xpath = new DOMXPath($xml);
$asd = $xml ->getElementsByTagName( "cd" );
$qwe = $xpath ->query('//catalog/cd');
foreach ($qwe as $qwe) {
$lastPrice = $xpath->query('//catalog/cd /disk[last()]/price')->item(0)->nodeValue;
$secondLastPrice = $xPath->query('//catalog/cd /disk[last()-1]/price')->item(0)->nodeValue;
}
?>
我如何从 $qwe 继续。获取每张 cd 的最后价格和倒数第二个价格?
【问题讨论】:
标签: php xml xpath domdocument domxpath