PHP DOM:getElementsByTagName返回具有此名称的所有节点(尽管我在特定标记内)

时间:2012-07-21 13:34:10

标签: php dom getelementsbytagname

我在寻找DAYS的答案!我还没有找到任何...... :( 这是我的XML示例:

    <?xml version="1.0" encoding="UTF-8"?>
    <Businesses>
    <Business NAME="Bus1">
    <DEAL ID="2">
    <title>My first Title</Title>
</DEAL>
    <DEAL ID="4">
    <title>My Second Title</Title>
</DEAL>
    </Business>
    <Business NAME="Bus2">
    <DEAL ID="2">
    <title>My 2nd Title</Title>
</DEAL>
    <DEAL ID="5">
    <title>My last Title</Title>
</DEAL>
    </Business>
    <Businesses>

我如何逐个解析这个xml?这是我的代码:

<?php 
  $doc = new domDocument();
  $doc->load("MyXML.xml"); //(The XML Above)
    $Businesses = $doc->documentElement;
    $ebus = $Businesses->childNodes;
    foreach ($ebus as $business) {

     if ($business instanceof domElement) {
     $busname=$business->getAttribute('NAME');
    $shelves = $Businesses->getElementsByTagName("DEAL"); //HERE IS THE PROBLEM

  foreach ($shelves as $deal) {

//Here i have all of the Businesses (I need to present only the first "NAME='Bus1'") for the first iteration! and so on..
}}}
?>

问题在于“getElementsByTagName”带来了所有“DEAL”节点,尽管我已经在第一个业务的内部了!!

我试过: $ shelves = $ Businesses-&gt; childNodes; //但它不正确

感谢您的帮助!!

1 个答案:

答案 0 :(得分:2)

您在$Businesses documentElement上呼叫它。您在开始时分配了它:

$Businesses = $doc->documentElement;

试试这个:

$shelves = $business->getElementsByTagName("DEAL");