Cómo reemplazar el texto de un nodo usando DOMDocument


Este es mi código que carga un archivo XML o cadena existente en un objeto DOMDocument:

$doc = new DOMDocument();
$doc->formatOutput = true;

// the content actually comes from an external file
$doc->loadXML('<rss version="2.0">
<channel>
    <title></title>
    <description></description>
    <link></link>
</channel>
</rss>');

$doc->getElementsByTagName("title")->item(0)->appendChild($doc->createTextNode($titleText));
$doc->getElementsByTagName("description")->item(0)->appendChild($doc->createTextNode($descriptionText));
$doc->getElementsByTagName("link")->item(0)->appendChild($doc->createTextNode($linkText));

Necesito sobrescribir el valor dentro de las etiquetas title, description y link. Las últimas tres líneas en el código anterior son mi intento de hacerlo; pero parece que si los nodos no están vacíos, el texto se "anexará" al contenido existente. Cómo puedo vaciar el contenido de texto de un nodo y añadir texto nuevo en una línea.

Author: Salman A, 2011-05-14

2 answers

Conjunto DOMNode::$nodeValue en su lugar:

$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
$doc->getElementsByTagName("description")->item(0)->nodeValue = $descriptionText;
$doc->getElementsByTagName("link")->item(0)->nodeValue = $linkText;

Esto sobrescribe el contenido existente con el nuevo valor.

 41
Author: lonesomeday,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-14 12:50:52

Como doub1ejack mencionó

$doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;

Dará error si $titleText = "& is not allowed in Node::nodeValue";

Así que la mejor solución sería

// clear the existing text content $doc->getElementsByTagName("title")->item(0)->nodeValue = "";

// then create new TextNode $doc->getElementsByTagName("title")->item(0)->appendChild($doc->createTextNode($titleText));

 4
Author: Raaghu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-27 04:03:27