基于子值解析simplexml


parse simplexml based on child value

可能重复:
PHP xpath-查找具有值的元素,并获取元素之前和之后的元素

我有以下xml:

<Table>
    <ID>100</ID>
    <Name>Fridge</Name>
    <Description>A cool refrigerator</Description>
</Table>
<Table>
    <ID>100</ID>
    <Name>Fridge</Name>
    <Description>Latest Refrigerator</Description>
</Table>
<Table>
    <ID>200</ID>
    <Name>Fridge</Name>
    <Description>Another refrigerator</Description>
</Table>

在上面的例子中,我想获得ID为100的节点的Name和Description的子值。xml文件中大约有1000个表节点。

如何解析整个xml并仅为ID等于100的节点获取Name和Description值?

到目前为止,我已经尝试了以下代码,但无法给出我想要的:

$source = 'Tables.xml';
$xmlstr = file_get_contents($source);
$sitemap = new SimpleXMLElement($xmlstr);
$sitemap = new SimpleXMLElement($source,null,true);
foreach($sitemap as $url) {
    if($url->ID == '100')
    {
        echo 'Name: '.(string)$url->Name.', Description: '.(string)$url->Description.'<br>';
    }
}

如果您获得所有Table标签并在其上循环,这应该非常简单:

// Assuming you already loaded the XML into the SimpleXML object $xml
$names_and_descriptions = array();
foreach ($xml->Table as $t) {
  if ($t->ID == 100) {
    echo $t->Name . " " . $t->Description . "'n";
    // Or stick them into an array or whatever...
    $names_and_descriptions[] = array(
      'name'=>$t->Name, 
      'description'=>$t->Description
    );
  }
}
var_dump($names_and_descriptions);