2

I have an XML file filled with 'producers.'

Here is a sample of what the file looks like:

<producer>
   <name>John Doe's Fish Emporium!</name>
   <owner>John Doe</owner>
   <address>
      <civic>123</civic>
      <mailing>Example Drive</mailing>
      <town>Halifax</town>
      <province>Nova Scotia</province>
      <postal>A1B 2C3</postal>
      <phone>902-123-4567</phone>
      <fax>902-098-7654</fax>
      <email>john@example.com</email>
      <website>www.example.com</website>
   </address>
   <products>
      <product>Pollock (Saithe)</product>
      <product>Flounder/Sole</product>
      <product>Salmon, Farm Raised</product>
      <product>Mussels, Blue</product>
   </products>
   <exports>
      <region>Europe</region>
      <region>North America</region>
      <region>Pacific Rim</region>
      <region>United States</region>
   </exports>
</producer> 

The user will enter a value into an html form, which will search the XML document for that keyword, then print out the entire producer. So for example if the user searches for the product Salmon, the search will spit out the entire producer above. How do I go about detecting where I am in the XML document, then echoing out the entire producer?

Thanks!

jasonaburton
  • 2,941
  • 7
  • 34
  • 48

3 Answers3

2

I am assuming your producer elements are direct children of producers root node. If not, adjust accordingly:

/producers/producer[descendant::*[contains(text(), "Salmon")]]

This will find all producer elements that have the text Salmon in any of it's child text nodes. This XPath allows you to search all the childnodes, e.g. region, town, product, etc - regardless of level.

See Implementing condition in XPath for boilerplate code.

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
0

This has already been answered many times, check out the related links to the right. Here's what you're going to need:

simplexml

DOM

XPath

mseancole
  • 1,662
  • 4
  • 16
  • 26
0

This might helpful :-

$obj   = simplexml_load_string(...);
$expr  = "/producer/products/product[contains(text(),'salmon')]/../..";
$found = $obj->xpath($expr);

enjoy, have fun!

ajreal
  • 46,720
  • 11
  • 89
  • 119