Как я могу редактировать XML-файл, используя DOMDocument и xquery - PullRequest
0 голосов
/ 05 ноября 2010

У меня есть XML-файл

<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>

Как я могу отредактировать XML-файл относительно id, используя DOMDocument и xquery для сохранения CDATA Заранее спасибо

текст ссылки

1 Ответ

2 голосов
/ 05 ноября 2010

Прежде всего, ваш документ имеет недопустимый синтаксис XML (тег </createCDATASection>).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>

Теперь вот решение для редактирования заголовка / описания для вашего мероприятия:

$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();
...