仅在php中显示具有特定属性的XML节点


display only nodes in XML with specific attributes in php

如果我有:

<listing>
<name>Bob</name>
<age>20</age>
<hair>red</hair>
</listing>
<listing>
<name>John</name>
<age>24</age>
<hair>black</hair>
</listing>

我如何编写我的PHP页面只显示列表,如果头发=黑色

这样它就只会拉入

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

谢谢

使用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();
}