PHP XML文件过滤器匹配

I am having a heck of a time getting this working...

What I want to do is filter a xml file by a city (or market in this case).

This is the xml data.

<itemset>
<item>
<id>2171</id>
<market>Vancouver</market>
<url>http://</url></item>
<item>
<id>2172</id>
<market>Toronto</market>
<url>http://</url></item>
<item>
<id>2171</id>
<market>Vancouver</market>
<url>http://</url></item>

This is my code...

<?php
$source = 'get-xml-feed.php.xml';

$xml = new SimpleXMLElement($source);

$result = $xml->xpath('//item/[contains(market, \'Toronto\')]');

while(list( , $node) = each($result)) {
    echo '//Item/[contains(Market, \'Toronto\')]',$node,"
";
}

?>

If I can get this working I would like to access each element, item[0], item[1] base on filtered results.

Thanks

I think this implements what you are looking for using XPath:

<?php
$source = file_get_contents('get-xml-feed.php.xml');

$xml = new SimpleXMLElement($source);

foreach ($xml as $node)
{
    $row = simplexml_load_string($node->asXML());
    $result = $row->xpath("//item/market[.='Toronto']");
    if ($result[0])
    {
        var_dump($row);
    }
}

?>

As another answer mentioned, unless you are wed to the use of XPath it's probably more trouble than it's worth for this application: just load the XML and treat the result as an array.

I propose using simplexml_load_file. The learning curve is less step than using the specific XML objects + XPath. It returns an object in the format you descibe.

Try this and you'll see what I mean:

<?php
$source = 'get-xml-feed.php.xml';

$xml = simplexml_load_file($source);

var_dump($xml);
?>

There is also simplexml_load_string if you just have an XML snippet.

<?php
$source = 'get-xml-feed.php.xml';

//$xml = new SimpleXMLElement($source);
$dom = new DOMDocument();
@$dom->loadHTMLFile($source);
$xml = simplexml_import_dom($dom);  

$result = $xml->xpath("//item/market[.='Toronto']/..");

while(list( , $node) = each($result)) {
   print_r($node);
}

?>

This will get you the parent nodeset when it contains a node with "Toronto" in it. It returns $node as a simplexml element so you will have to deal with it accordingly (I just printed it as an array).