将DOM对象中的节点附加到另一个DOM

时间:2011-06-12 01:22:00

标签: php xml dom

这是我最好的,我可以想象需要做什么。但我不知道如何让它发挥作用。

$ xml和$ xmlfile都是DOM对象/ XML。 $ xml是我想要追加到$ mxlfile的数据的来源。

$ xml作为dom对象从另一个函数发送到该函数。

这就是xml给我的方式。

<?xml version="1.0" encoding="utf-8"?>
<!-- Automatically generated data from EVE-Central.com -->
<!-- This is the new API :-) -->
<evec_api version="2.0" method="marketstat_xml">
  <marketstat>
    <type id="18">
      <all>
        <volume>1934078988.00</volume>
        <avg>98.31</avg>
        <max>26721.00</max>
        <min>0.53</min>
        <stddev>1339.78</stddev>
        <median>26.31</median>
        <percentile>0.00</percentile>
      </all>
      <buy>
        <volume>1894081100.00</volume>
        <avg>20.77</avg>
        <max>31.31</max>
        <min>0.53</min>
        <stddev>7.25</stddev>
        <median>26.00</median>
        <percentile>28.17</percentile>
      </buy>
      <sell>
        <volume>39997888.00</volume>
        <avg>34.32</avg>
        <max>26721.00</max>
        <min>4.01</min>
        <stddev>2339.28</stddev>
        <median>29.80</median>
        <percentile>26.76</percentile>
      </sell>
    </type>
    <type id="ectera">
    </type>
  </marketstat>
</evec_api>

在这里我的功能部分我无法工作。

$xml->preserveWhiteSpace = FALSE;
$xml->formatOutput = TRUE;
if(is_file($file)){
$xmlfile = new DOMDocument;
$xmlfile->load($file);
$dst = $xmlfile->getElementsByTagName('marketStat');
foreach($xml->getElementsByTagName('type') as $child){
 $dst->appendChild($xmlfile->importNode($child));}
$xmlfile->save($file);
}

我知道有些不对劲,但我只是在教自己xml和dom,所以非常感谢帮助。

1 个答案:

答案 0 :(得分:0)

<?php

if(is_file($file))
{
    $xmlfile = new DOMDocument;

    $xml->preserveWhiteSpace = FALSE;
    $xml->formatOutput = TRUE;

    $xmlfile->load($file);

    $dst = $xmlfile->getElementsByTagName('marketStat');
    $parentLength  = $dst->length;

    for($i=0; $i< $parentLength ; $i++)
    {
        foreach($xmlfile->getElementsByTagName('type') as $child)
        {
            $dst->item($i)->appendChild($child);
        }
    }
    $xmlfile->save($file);
}

您的代码有两个错误

  1. 您可以在创建文档后设置DOM解析器的选项。

  2. 您不能在DOM对象列表中使用appendChild。您必须逐个将它们添加到单个DOM元素上。