0

我想使用 cakephp 或使用 DOM 元素的 Php 更改以下 xml 文件的格式。

<child>
 <Lunchmenu>
   <id>1</id>
   <lunch_date>2013-10-25</lunch_date>
   <class_id>1</class_id>
   <batch_id/>
   <school_id>1</school_id>
   <Eatable>
   <eatable_name>Noodles</eatable_name>
   </Eatable>
 </Lunchmenu>
 <Lunchmenu>
  <id>2</id>
  <lunch_date>2013-10-24</lunch_date>
  <class_id/>
  <batch_id/>
  <school_id>1</school_id>
  <Eatable>
   <eatable_name>Apples</eatable_name>
  </Eatable>
 </Lunchmenu>
 <Lunchmenu>
    <id>2</id>
    <lunch_date>2013-10-24</lunch_date>
    <class_id/>
    <batch_id/>
    <school_id>1</school_id>
    <Eatable>
    <eatable_name>Orange</eatable_name>
    </Eatable>
  </Lunchmenu>
</child>

<child>
 <Lunchmenu>
   <id>1</id>
   <lunch_date>2013-10-25</lunch_date>
   <class_id>1</class_id>
   <batch_id/>
   <school_id>1</school_id>
   <Eatable>
   <eatable_name>Noodles</eatable_name>
   </Eatable>
 </Lunchmenu>
<Lunchmenu>
  <id>2</id>
  <lunch_date>2013-10-24</lunch_date>
  <class_id/>
  <batch_id/>
  <school_id>1</school_id>
    <Eatable>
     <eatable_name>Apples</eatable_name>
    </Eatable>
    <Eatable>
     <eatable_name>Orange</eatable_name>
    <Eatable>
 </Lunchmenu>

我试过但没有成功。

4

2 回答 2

0

您可以使用 PHP 的 XSLT 处理器功能将一种 XML 格式转换为另一种格式。

更多信息可以在这里找到:

http://php.net/manual/en/xsltprocessor.transformtoxml.php

或者,一种更加劳动密集型的方法是使用 XMLReader 和 XMLWriter 类以编程方式将 XML 格式化为您需要的格式。

http://www.php.net/manual/en/book.xmlwriter.php

詹姆士

于 2013-10-25T15:21:09.220 回答
0

在你的情况下,我将使用这个 PHP 函数:simplexml_load_string

$xml_parsed = simplexml_load_string('<your xml>');

然后,像这样使用它:

//1st regroup lunchmenu by DATE or by ID I don't know what you want
$lunch = array();
foreach($xml_parsed->Lunchmenu as $lunchmenu) {
   $lunch[$lunchmenu->id][] = $lunchmenu;
}
//Then reform XML
foreach($lunch as $lunchmenus) {
    $lunchmenu = $lunchmenus[0];
    $finalXML .= "<Lunchmenu>
                  <id>".$lunchmenu->id."</id>
                  <lunch_date>".$lunchmenu->lunch_date."</lunch_date>
                  <class_id>".$lunchmenu->class_id."</class_id>
                  <batch_id/>
                  <school_id>".$lunchmenu->school_id."</school_id>";
    foreach($lunchmenus as $lunchmenu) {
        $finalXML .= "<Eatable>
                     <eatable_name>".$lunchmenu->eatable_name."</eatable_name>
                      </Eatable>";
    }
    $finalXML .= '</Lunchmenu>';
}
$finalXML = '<child>';
$finalXML .= '</child>';

echo $finalXML;

我没有测试任何东西......这只是为了提供帮助!

于 2013-10-25T15:15:06.257 回答