1

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,"\n";
}

?>

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

Thanks

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think we may be trying to get the parent node that contains the specific node. For that you would need this xpath expressions: '//item/market[.='Toronto']/..'
0

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.

Comments

0
<?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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.