PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
to the current date when I'll enter a php page.
I know how to load an element and change it but I can't figure out how to load the comment and edit it
this is how I load and edit an element
//Load XML and set some config
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$getName="$file_name.xml";
$xml->load($getName);
//Get item Element
$element = $xml->getElementsByTagName('site')->item(0);
//Load child elements
$name = $element->getElementsByTagName('Visit')->item(0);
//Change values
$name->nodeValue = 'test';
//Replace old elements with new
$element->replaceChild($name, $name);
I am not sure there is a way. I would recommend using fopen() and the fgets() to read lines from the file. That will be faster. Or you could read the whole file and do string manipulations.
/**
* Gets comment child nodes from the given node.
*
* @param DOMNode $node
* @param int $depth
* How deep to go in the hierarchy (number of nodes, including the original
* node). A number less than 1 means virtually unlimited. Default 0.
* @return array
* An array of DOMComments
*/
function getComments (DOMNode $node, $depth = 0) {
$children = array();
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $child) {
if ($child->nodeName == '#comment') {
$children[] = $child;
} else if ((int)$depth != 1) {
foreach(getComments($child, $depth - 1) as $comment) {
$children[] = $comment;
}
}
}
}
return $children;
}
$comments = getComments($xml, 1);
echo $comments[0]->nodeValue;
I don't know why DOMDocument::getElementsByTagName() doesn't find comments when given "#comment" as a name. That is the name returned by DOMNode::nodeName, and there is a precedent for accepting special values: "*".