Count items by condition with XML and PHP?

匆匆过客 提交于 2020-01-21 20:11:31

问题


I would like to get the count of only items inside this file with sellingstatus->sellingstate of EndedWithSales ONLY, and perhaps also get the count for EnededWithoutSales.

<sellingStatus>
    <currentPrice currencyId="USD">25.0</currentPrice>
    <convertedCurrentPrice currencyId="USD">25.0</convertedCurrentPrice>
    <bidCount>1</bidCount>
    <sellingState>EndedWithSales</sellingState>
</sellingStatus>

How would I go about passing this argument in php?

Here is a link to the sample of XML: http://developer.ebay.com/DevZone/finding/CallRef/Samples/findCompletedItems_basic_out_xml.txt.

Can anyone help out?


回答1:


First off, you need to access the url thu file_get_contents, Consider this example:

$url = 'http://developer.ebay.com/DevZone/finding/CallRef/Samples/findCompletedItems_basic_out_xml.txt';

// access the url and get that file
$contents = file_get_contents($url);

// convert it to an xml object
$contents = simplexml_load_string($contents);

$count = 0; // initialize counter

// loop and search for that
foreach($contents->searchResult->item as $key => $value) {

    if(isset($value->sellingStatus->sellingState) && $value->sellingStatus->sellingState == 'EndedWithSales') {
        // if that key exists and is contains EndedWithSales, increment it
        $count++;
    }
}

// at the end of the loop echo it or whatever you wanted to do
echo "<script>alert('You have $count ocurrances of EndedWithSales in this XML');</script>";



回答2:


You can load the XML into an DOMDocument, create an Xpath instance for it an just fetch the count.

$url = 'http://developer.ebay.com/DevZone/finding/CallRef/Samples/findCompletedItems_basic_out_xml.txt';
$dom = new DOMDocument();
$dom->load($url);
$xpath = new DOMXpath($dom);

// register a prefix for the namespace used in the document 
$xpath->registerNamespace('ebay', 'http://www.ebay.com/marketplace/search/v1/services');

var_dump(
   $xpath->evaluate(
     'count(
       //ebay:searchResult[1]
       /ebay:item[
         ebay:sellingStatus/ebay:sellingState = "EndedWithSales"
       ]
      )'
   )
);

Output:

double(2)

Xpaths count() function returns the number of nodes in defined by an expression.

The first searchResult element in the document:

//ebay:searchResult[1]

The item elements in the first searchResult

//ebay:searchResult[1]/ebay:item

Items with a sellingState "EndedWithSales"

//ebay:searchResult[1]/ebay:item[ebay:sellingStatus/ebay:sellingState = "EndedWithSales"]



来源:https://stackoverflow.com/questions/23510323/count-items-by-condition-with-xml-and-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!