-2

如果我有:

<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>

谢谢

4

1 回答 1

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();
}
于 2013-05-21T14:44:20.747 回答