【问题标题】:How to get the value from XML file in PHP?如何从 PHP 中的 XML 文件中获取值?
【发布时间】:2017-05-07 07:48:33
【问题描述】:

这是我的 xml 代码

<Hotelobjekt xmlns="http://www.dcs-caesar.de/hoteldaten" CRSSperre="false" Buchungssperre="false">
      <Hotelcode>AYTBLK0038</Hotelcode>
      <Hotelname>LIMAK ATLANTIS DE LUXE HOTEL &amp;amp; RESORT</Hotelname>    
    <Saisondefinition Saisonkuerzel="W16" DatumVon="2016-11-01" DatumBis="2017-04-06">
        <Saisonzeit Nummer="1">
          <Zeitraum DatumVon="2016-11-01" DatumBis="2016-11-18"/>
          <Zeitraum DatumVon="2016-12-25" DatumBis="2016-12-31"/>
        </Saisonzeit>
        <Saisonzeit Nummer="2">
          <Zeitraum DatumVon="2017-01-01" DatumBis="2017-03-06"/>
          <Zeitraum DatumVon="2016-11-19" DatumBis="2016-12-24"/>
        </Saisonzeit>
        <Saisonzeit Nummer="3">
          <Zeitraum DatumVon="2017-03-07" DatumBis="2017-04-06"/>
        </Saisonzeit>
      </Saisondefinition>
    </Hotelobjekt>



$items = simplexml_load_file($url);
print_r($items); // it's okey works

数组输出;

SimpleXMLElement 对象 ( [@attributes] => 数组 ( [CRSSperre] => 假 [Buchungssperre] => 假) [酒店代码] => AYTBLK0038 [酒店名称] => 利马克亚特兰蒂斯豪华酒店及度假村 [Saisondefinition] => SimpleXMLElement 对象([@attributes] => 数组 ( [Saisonkuerzel] => W16 [DatumVon] => 2016-11-01 [DatumBis] => 2017-04-06 ) [Saisonzeit] => 数组 ( [0] => SimpleXMLElement 对象 ( [@attributes] => 数组 ( [Nummer] => 1 ) [Zeitraum] => 数组 ( [0] => SimpleXMLElement 对象 ( [@attributes] => 数组 ( [DatumVon] => 2016-11-01 [DatumBis] => 2016-11-18 ) ) [1] => SimpleXMLElement 对象 ( [@attributes] => 数组 ( [DatumVon] => 2016-12-25 [DatumBis] => 2016-12-31 ) ) ) [1] => SimpleXMLElement 对象 ([@attributes] => 数组 ( [Nummer] => 2 ) [Zeitraum] => 数组 ( [0] => SimpleXMLElement 对象([@attributes] => 数组([DatumVon] => 2017-01-01 [DatumBis] => 2017-03-06 ) ) [1] => SimpleXMLElement 对象 ( [@attributes] => 数组 ( [DatumVon] => 2016-11-19 [DatumBis] => 2016-12-24 ) ) ) ) [ 2] => SimpleXMLElement 对象 ( [@attributes] => 数组 ( [Nummer] => 3 ) [Zeitraum] => SimpleXMLElement 对象 ( [@attributes] => 数组 ( [DatumVon] => 2017-03-07 [DatumBis] => 2017-04-06 ) ) ) ) )

echo $items->Hotelcode."<br>";
echo $items->Hotelname."<br>";

此代码有效,但我想获取其他代码

<Zeitraum DatumVon="2017-01-01" DatumBis="2017-03-06"/>

【问题讨论】:

    标签: php mysql xml database


    【解决方案1】:

    只需对子项进行循环

    $xml = simplexml_load_string($string);
    foreach($xml->Saisondefinition->Saisonzeit as $Saisonzeit) {
       echo $Saisonzeit['Nummer'] . "<br>\n";
       foreach($Saisonzeit->Zeitraum  as $Zeitraum ) { 
           echo $Zeitraum['DatumVon'] . ' - ' . $Zeitraum['DatumBis'] . "<br>\n";
       }
    }
    

    Demo on eval.in

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多