简体   繁体   中英

how to give php-xml total count id

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>';
            }
        }
    }

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);

Output

float(1)
int(1)

Xpath Expressions

  • 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'])

Try this:

$xmlArray2 = array();
foreach($xml->Product as $product2) {
    if( (string)$product->Book == 'PHP' ) {
        $xmlArray2[] = array("PHP" => (string)$product->Book);
    }
}
$total = count($xmlArray2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM