如何保存到XML文件

时间:2018-02-07 13:52:35

标签: php xml

我有2个文件: 这是我想要的方式。但我不知道如何将结果写回xml文件。 Xml应包含原始文件中的所有字段,但按名称排序的顺序不同

    <?xml version="1.0" encoding="windows-1250"?>
    <ProgramData>
      <DeviceGroup Name="Wrocław">
        <Device>
          <Comunicator/>
          <Identity>
            <response>
              <identity_device>
                <modules>
                  <module/>
                  <module/>
                  <module/>
                  <module/>
                </modules>
                <primarylog/>
                <secondarylog/>
                <configfiles/>
              </identity_device>
            </response>
          </Identity>
        </Device>
      </DeviceGroup>
      <DeviceGroup Name="Lublin">
        <Device>
          <Comunicator/>
          <Identity>
            <response>
              <identity_device>
                <modules>
                  <module/>
                  <module/>
                  <module/>
                  <module/>
                </modules>
                <primarylog/>
                <secondarylog/>
                <configfiles/>
              </identity_device>
            </response>
          </Identity>
        </Device>
      </DeviceGroup>
    </ProgramData>

PHP文件:

    <?php
    $xml = simplexml_load_file('obiekty.xml');
    $ob = $xml->xpath('/ProgramData/DeviceGroup');
    function sort_ob($t1, $t2) {
        return strcmp($t1['Name'], $t2['Name']);
    }
    usort($ob, 'sort_ob');
    var_dump($ob);
    ?>

1 个答案:

答案 0 :(得分:1)

您必须创建DomDocument并将已排序的数据导入其中。

以下是保存已排序数据的代码:

// Your code
$xml = simplexml_load_file('obiekty.xml');
$ob = $xml->xpath('/ProgramData/DeviceGroup');
function sort_ob($t1, $t2) {
    return strcmp($t1['Name'], $t2['Name']);
}
usort($ob, 'sort_ob');

// Code to save $ob array :
$doc = new DomDocument("1.0", "windows-1250") ;
$rnode = $doc->createElement("ProgramData") ; // recreate the root node
$doc->appendChild($rnode) ;
foreach ($ob as $elm) {
    $node = dom_import_simplexml($elm) ;
    $node = $doc->importNode($node, true) ; // true to keep "deep" data.
    $rnode->appendChild($node) ;
}
$doc->save("out.xml") ; // save the recreated XML into a file.

out.xml将包含:

<?xml version="1.0" encoding="windows-1250"?>
<ProgramData>
  <DeviceGroup Name="Lublin">
    <!-- skipped content but present in file -->
  </DeviceGroup>
  <DeviceGroup Name="Wrocław">
    <!-- skipped content but present in file -->
  </DeviceGroup>
</ProgramData>