-2

if i have:

<listing>
<name>Bob</name>
<age>20</age>
<hair>red</hair>
</listing>

<listing>
<name>John</name>
<age>24</age>
<hair>black</hair>
</listing>

how do i code my php page to only display listings if hair = black

so that it would only pull in

<listing>
<name>John</name>
<age>24</age>
<hair>black</hair>
</listing>

Thanks

user2405912
  • 65
  • 1
  • 9
  • How are you currently parsing the XML? It’s helpful to see what you have already. – Ry- May 21 '13 at 14:25
  • I am a newb, but it is pulling in as a standard xml file like this [link]http://www.w3schools.com/xml/simple.xml – user2405912 May 21 '13 at 14:31

1 Answers1

0

Use XPath.

// First, your XML must be wraped with some root tag.
$data = <<<XML
<root>
    <listing>
        <name>Bob</name>
        <age>20</age>
        <hair>red</hair>
    </listing>

    <listing>
        <name>John</name>
        <age>24</age>
        <hair>black</hair>
    </listing>
</root>
XML;

// Instancing the SimpleXMLElement within the XML(obviously)
$xml = new SimpleXMLElement($data);

// XPath
$xpath = $xml->xpath("listing[contains(hair,'black')]"); 
/**
 * eXplained XPath:
 *      <listing> that 
 *              <hair>'s content is equal black
 */

foreach($xpath as $node){
    // just for fun echoes the <results> node
    echo $node->asXml();
}
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315