0

I have a xml file

<events date="06-11-2010">
    <event id="8">
      <title>Proin porttitor sollicitudin augue</title>
      <description><![CDATA[Lorem  nunc.]]></description>
    </event>
  </events>
  <events date="16-11-2010">
    <event id="4">
      <title>uis aliquam dapibus</title>
      <description><![CDATA[consequat vel, pulvinar.</createCDATASection></description>
    </event>
  <event id="1"><title>You can use HTML and CSS</title>
  <description><![CDATA[Lorem ipsum dolor sit amet]]></description></event></events>

How i can edit the xml file with respect to id using DOMDocument and xquery for preserving CDATA Thanks in advance

link text

2
  • What do you want to do? Please add some more detail to your question. Commented Nov 5, 2010 at 13:29
  • I want to edit title or description.Description is with CDATA with a given value of event id Commented Nov 5, 2010 at 13:31

1 Answer 1

2

First of all, your document has invalid XML syntax (the </createCDATASection> tag). FTFY:

<events date="06-11-2010">
  <event id="8">
    <title>Proin porttitor sollicitudin augue</title>
    <description><![CDATA[Lorem  nunc.]]></description>
  </event>
</events>
<events date="16-11-2010">
  <event id="4">
    <title>uis aliquam dapibus</title>
    <description><![CDATA[consequat vel, pulvinar.]]></description>
  </event>
  <event id="1">
    <title>You can use HTML and CSS</title>
    <description><![CDATA[Lorem ipsum dolor sit amet]]></description>
 </event>
</events>

Now, here's a solution to edit title/description for your event:

$dom = new DOMDocument;
$dom->loadXML(file_get_contents('doc.xml'));

$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//event[@id="4"]/title | //event[@id="4"]/description');

// title
$node = $nodes->item(0);
$node->nodeValue = 'hello world';

// description
$node = $nodes->item(1);
$cdata = $node->firstChild;
$cdata->replaceData(0, strlen($cdata->data), 'hello world description');

print $dom->saveXML();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.