我对xml有问题,我正在使用php。对我来说需要总id。用这个代码获得所有产品的总id。
$xmlArray = array();
foreach($xml->Product as $product) { $xmlArray[] = array("productID" => (string)$product->Book); }
$total = count($xmlArray);
但对我来说,只需要php图书总id,我的php图书代码总id
$xmlArray2 = array();
foreach($xml->Product as $product2) { $xmlArray2[] = array("PHP" => (string)$product->Book); }
$total = count($xmlArray2);
但要给出所有产品的总id。所有代码:
$inPage = 10;
$currentRecord = 10;
$xml = new SimpleXMLElement('http://examplesite.com/xmlinfo.xml', 0, true);
$xmlArray = array();
foreach($xml->Product as $product) { $xmlArray[] = array("prouctID" => (string) $product->Book); }
$total = count($xmlArray);
$toplamPage = ceil($total / $inPage);
foreach($xml->Product as $value) {
if($value->Book == "PHP") {
$currentRecord += 1;
if($currentRecord > ($page * $inPage) && $currentRecord < ($page * $inPage + $inPage)) {
echo '<div class="BrandTab">';
echo '<a href="product.php?productID=' . $value->UrunID . '"><img src="' . $value->ImageName . '" style="width:130px;height:200px;/></a>';
echo '<article>';
echo '<div class="ok"></div>';
echo '<p>' . $value->ProductName . '</p>';
echo '</article>';
echo '</div>';
}
}
}
使用DOM和XPath,可以直接使用DOMXpath::evaluatate()获取值。您还可以获取经过筛选的产品列表。与使用API函数相比,您可以避免许多循环和条件。
$xml = <<<'XML'
<Products>
<Product>
<Book>PHP</Book>
<Product>
</Product>
<Book>JavaScript</Book>
</Product>
</Products>
XML;
$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
var_dump($xpath->evaluate('count(//Product[normalize-space(Book) = "PHP"])'));
var_dump($xpath->evaluate('//Product[normalize-space(Book) = "PHP"]')->length);
输出
float(1)
int(1)
Xpath表达式
正在获取所有
Product
元素//Product
。。。其中CCD_ 3元素等于CCD_
//Product[Book = 'PHP']
。。。在规范化空白之后
//Product[normalize-space(Book) = 'PHP']
。。。并以数字形式返回节点计数:
count(//Product[normalize-space(Book) = 'PHP'])
试试这个:
$xmlArray2 = array();
foreach($xml->Product as $product2) {
if( (string)$product->Book == 'PHP' ) {
$xmlArray2[] = array("PHP" => (string)$product->Book);
}
}
$total = count($xmlArray2);