如何使用php在xml中添加/追加字符串数据

时间:2016-05-21 12:41:06

标签: php xml

以下是我的样本xml数据

 <?xml version="1.0"?>
<catalog>
   <book>
      <book NAME="ci_id">
        <PVAL><![CDATA[55190]]></PVAL>
      </book>
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
   </book>
   <book>
      <book NAME="ci_id">
        <PVAL><![CDATA[55191]]></PVAL>
      </book>
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
   </book>
   <book>
      <book NAME="ci_id">
        <PVAL><![CDATA[55192]]></PVAL>
      </book>
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
   </book>

   <book>
      <book NAME="ci_id">
        <PVAL><![CDATA[55194]]></PVAL>
      </book>
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
   </book> 
</catalog>

我的要求是我必须根据pval id条件删除父节点(即&lt; book&gt;到&lt; / book&gt;)(例如:这里我删除pval = 55192)并且我需要更新新节点。

在下面的代码中,我已经基于pval成功删除了父节点,但是我无法添加新节点(即,它是一个字符串值)。请指导我。

$xmlFileToLoad   =  'client_temp/endeca_xml_search_feed/product/testing.xml';
      $xmlFileToSave   =  'client_temp/endeca_xml_search_feed/product/testing-modified.xml';

      $cdata_text = '
      <book>
         <book NAME="ci_id">
            <PVAL><![CDATA[78965]]></PVAL>
         </book>
         <author>testing</author>
         <title>Md kaif khan</title>
         <genre>kkkk</genre>
         <price>5.95</price>
         <publish_date>2016-09-10</publish_date>
         <description>Just i am testing.</description>
      </book>';

      $dom = new DOMDocument();
      $dom->load($xmlFileToLoad);
      $xpath = new DOMXPath($dom);

    function findStopPointByName($xml, $query) {
      $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZAZSCZCÓL";
      $lower = "abcdefghijklmnopqrstuvwxyzazscznól";
      $arg_query    = "translate(text(), '$upper', '$lower')";
      $q = "//book[book/PVAL[contains($arg_query, '$query')]]" ."\n";
      return $xml->query($q);
    }

    foreach(findStopPointByName($xpath,'55192') as $node)
    {
      $node->parentNode->removeChild($node);
       $node->appendChild( 
     $doc->createTextNode( $cdata_text ) );  
    }

    $dom->save($xmlFileToSave);

请告诉我如何添加节点(即字符串数据。这里是$ cdata_text)。

1 个答案:

答案 0 :(得分:1)

   foreach(findStopPointByName($xpath,'55192') as $node)
    {
      // Save parent - after removing node we will use it
      $parent = $node->parentNode;
      $parent->removeChild($node);

      // Load XML from text. You cann't append text, only node
      $data = new DOMDocument();
      $data->loadXML($cdata_text);

      // Import all new XML to our one and append to saved parent
      $ndata =  $dom->importNode($data->documentElement, true);   
      $parent->appendChild($ndata); 
    }