我有xml的问题,我正在使用PHP。对我来说需要总id。使用此代码获取所有产品的总ID。
$xmlArray = array();
foreach($xml->Product as $product) { $xmlArray[] = array("productID" => (string)$product->Book); }
$total = count($xmlArray);
但对我来说只需要php book total id,我的php书籍总代码为
$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>';
}
}
}
答案 0 :(得分:1)
使用DOM和XPath,您可以使用DOMXpath :: evaluate()直接获取值。您也可以获取已过滤的产品列表。与使用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)
获取所有Product
元素...
//Product
... Book
元素等于PHP
...
//Product[Book = 'PHP']
...规范化空格后...
//Product[normalize-space(Book) = 'PHP']
...并将节点计数作为数字返回:
count(//Product[normalize-space(Book) = 'PHP'])
答案 1 :(得分:0)
试试这个:
$xmlArray2 = array();
foreach($xml->Product as $product2) {
if( (string)$product->Book == 'PHP' ) {
$xmlArray2[] = array("PHP" => (string)$product->Book);
}
}
$total = count($xmlArray2);