XPATH检查当前节点的单个属性,然后返回许多属性

时间:2015-07-28 02:50:29

标签: php xml xpath

我想搜索XML数据并仅返回符合我标准的一些节点。我当前测试中的大多数代码都是从这个站点获取的,但是我在编写它时遇到的问题最简单。

我知道XPATH是最有效的,这是我的数据和我的示例代码。

数据提供如下:

<pre>
  <Performances>
    <Performance
      performance_id="100042434"
      business_date="08232015"
      show_datetime="1335" 
      reserved_seating="0" 
      auditorium_layout_id="0" 
      performance_number="37654" 
      ticket_price_scheme_index="13" 
      auditorium_index="12" 
      stadium_seat_flag="0" 
      dolby_sound_flag="0" 
      dts_sound_flag="0" 
      thx_sound_flag="0" 
      performance_status_code="0" 
      atm_purchase_flag="1" 
      remote_purchase_flag="1" 
      allow_pass_flag="1" 
      disallow_discount_flag="0" 
      special_engagement_flag="0" 
      feature_code="1502    "
      extended_performance_status_code="O"
    />
  </Performances>
</pre>

性能是我需要检查的元素......几百个。

我的代码是

$XML = simplexml_load_file("BoxOfcXML.326") or die("Error: Cannot create object");

$XMLResults = $XML->xpath('/BoxOfc/Performances/Performance');
foreach($XMLResults as $Result) {
    $Aud = $Result->xpath('//Attribute[@name="auditorium_index"]');

    if($Aud) {
        // because we have a list of elements even if there's one result
        $attributes = $Aud[0]->attributes();
        $AudID = $attributes['value'];
    }
    else {
    // No Author
    }
}

但我知道XPath不正确。我已尝试过不同级别的等等,但我知道我错了。

我可以使用下面的代码获取并比较我需要的数据。但是如果我要使用这种方法,我必须在同一个节点上重新运行循环,一旦我的条件得到满足,因为我的代码无效。如果我只是想检查日期,它会工作正常。但是我需要检查日期,剧院ID,然后再返回一些元素。

foreach ($perfID->attributes() as $a => $b) {
    if ($a == 'business_date') {
        //collect data we need from each att 
        //set flag if date is today
        //spit it out at the end - 
        if ($b == $today) { echo $b . "<br><br>"; }
    }
}

====== EDIT ======= 这是工作代码,将获得我需要的东西。我只需要假设有一种更清洁的方法。

$today = date("mdY");
$XML = simplexml_load_file("BoxOfcXML.326") or die("Error: Cannot create object");
$XMLResults = $XML->xpath('/BoxOfc/Performances/Performance');
foreach($XMLResults as $Result) {
    $Details = $Result; //Duplicate it in order to nest the details loop
foreach ($Result->attributes() as $a => $b) {
        if ($a == 'business_date') {    
            if ($b == $today) { 

                foreach ($Details->attributes() as $a => $b) {
                        switch ($a) {
                            case "business_date":
                                echo "$a $b <br>";
                                break;
                            case "show_datetime":
                                echo "$a $b <br>";
                                break;
                            case "auditorium_index":
                                echo "$a $b <br>";
                                break;
                            case "feature_code":
                                echo "$a $b<br><br>";
                                break;

                        }

                }
            }
        }
    }

}

1 个答案:

答案 0 :(得分:2)