根据子值解析simplexml

时间:2012-09-06 12:50:48

标签: php xml simplexml

  

可能重复:
  PHP xpath - find element with a value and also get elements before and after element

我有以下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的节点的名称和描述的子值。 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>';
    }
}

1 个答案:

答案 0 :(得分:2)

如果您获得所有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);