代码之家  ›  专栏  ›  技术社区  ›  Rakward

php simplexml:当节点返回空白时加载字符串?(simpleXML加载字符串)

  •  0
  • Rakward  · 技术社区  · 16 年前

    我正试图通过将字符串作为XML节点加载来向XML节点添加子节点,但由于某种原因,它返回一个空值…

    // Load xml
    $path = 'path/to/file.xml';
    $xml = simplexml_load_file($path);
    
    // Select node
    $fields = $xml->sections->fields;
    
    // Create new child node
    $nodestring = '<option>
               <label>A label</label>
               <value>A value</value>
               </option>';
    
    // Add field
    $fields->addChild('child_one', simplexml_load_string($nodestring));
    

    出于某种原因,添加了child_one,但没有内容,尽管它确实添加了换行符。

    尽管当我在simpleXML加载字符串($nodestring)上执行var_导出时,我得到:

        SimpleXMLElement::__set_state(array(
       'label' => 'A label',
       'value' => 'A value',
        ))
    

    所以我不知道我做错了什么…

    编辑:

    示例XML文件:

    <config>
        <sections>
            <fields>
                text
            </fields>
        </sections> 
    </config>
    

    sampe$xml-尝试添加子节点后的文件:

    <config>
        <sections>
            <fields>
                text
            <child_one>
    
    
    </child_one></fields>
        </sections> 
    </config>
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Josh Davis    16 年前

    simpleXML无法操作节点。可以从值创建新节点,但不能创建节点,然后将此节点复制到其他文档。

    这个问题有三种解决方案:

    1. 使用 DOM 相反。
    2. 直接在正确的文档中创建节点,例如

      $option = $fields->addChild('option');
      $option->addChild('label', 'A label');
      $option->addChild('value', 'A value');
      
    3. 使用库,如 SimpleDOM ,这将允许您在simpleXML元素上使用dom方法。

    在您的示例中,解决方案2似乎是最好的。

        2
  •  0
  •   Rakward    16 年前

    我使用的代码:

    // Load document
    $orgdoc = new DOMDocument;
    $orgdoc->loadXML("<root><element><child>text in child</child></element></root>");
    
    // Load string
    $nodestring = '<option>
           <label>A label</label>
           <value>A value</value>
           </option>';
    
    $string = new DOMDocument;
    $string->loadXML($nodestring);
    
    // Select the element to copy
    $node = $string->getElementsByTagName("option")->item(0);
    
    // Copy XML data to other document
    $node = $orgdoc->importNode($node, true);
    $orgdoc->documentElement->appendChild($node);
    
    推荐文章