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

时间:2013-05-21 14:23:30

标签: php xml xml-parsing

如果我有:

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

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

如何将我的php页面编码为仅在hair = black

时显示列表

所以它只会拉入

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

由于

1 个答案:

答案 0 :(得分:0)

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