Reputation: 5
i have problem with xml and i am working with php. For me need total id. With this code get total id all products.
$xmlArray = array();
foreach($xml->Product as $product) { $xmlArray[] = array("productID" => (string)$product->Book); }
$total = count($xmlArray);
But for me need only php books total id, my codes for php books total id
$xmlArray2 = array();
foreach($xml->Product as $product2) { $xmlArray2[] = array("PHP" => (string)$product->Book); }
$total = count($xmlArray2);
but give total id all products. And all codes:
$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>';
}
}
}
Upvotes: 0
Views: 101
Reputation: 19512
With DOM and XPath you can fetch the value directly using DOMXpath::evaluate(). You can fetch a filtered list of the products, too. Compared to using API functions you are able to avoid a lot of loops and conditions.
$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)
Fetch all Product
elements ...
//Product
... with the Book
elements equal to PHP
...
//Product[Book = 'PHP']
... after normalizing the whitespaces ...
//Product[normalize-space(Book) = 'PHP']
... and return the node count as number:
count(//Product[normalize-space(Book) = 'PHP'])
Upvotes: 1
Reputation: 1317
Try this:
$xmlArray2 = array();
foreach($xml->Product as $product2) {
if( (string)$product->Book == 'PHP' ) {
$xmlArray2[] = array("PHP" => (string)$product->Book);
}
}
$total = count($xmlArray2);
Upvotes: 0