Hello guys, I have an XML file, with the following structure:
<?xml version="1.0"?>
<parameters>
<param>
<name>site</name>
<type>text</type>
</param>
<param>
<name>filetype</name>
<type>text</type>
</param>
<param>
<name>intitle</name>
<type>text</type>
</param>
<parameters>
And foreach <param> label I need to insert a new label called <alias> someting like:
<param>
<alias>filetype</alias>
<name>filetype</name>
<type>text</type>
</param>
And, by default, the value for "alias" will be the same as the value inside "name"
Could someone help with this??
thanks,
How to modify an XML file using DOM
Moderator: General Moderators
Re: How to modify an XML file using DOM
SimpleXML makes the world go 'round... as long as you have PHP 5.
My DOM solution is bothersome, so if you can't do that then I'd try regular expressions:
Code: Select all
$xml = new SimpleXML($file);
foreach ($xml->param as $p) {
$alias = (string)$p->name;
$p->appendChild("alias", $alias);
}Code: Select all
$xml = file_get_contents($file);
$xml = preg_replace("#<name>(.*?)</name>#s", "<alias>\$1</alias>\n\$0", $xml);Re: How to modify an XML file using DOM
tasairis wrote:SimpleXML makes the world go 'round... as long as you have PHP 5.My DOM solution is bothersome, so if you can't do that then I'd try regular expressions:Code: Select all
$xml = new SimpleXML($file); foreach ($xml->param as $p) { $alias = (string)$p->name; $p->appendChild("alias", $alias); }Code: Select all
$xml = file_get_contents($file); $xml = preg_replace("#<name>(.*?)</name>#s", "<alias>\$1</alias>\n\$0", $xml);
Well, I have done somthing like:
function insertXMLNodeAlias($myxml)
{
$doc = new DOMDocument();
$doc->loadXML($myxml);
$param_list = $doc->getElementsByTagName( "param" );
foreach($param_list as $param)
{
$name = $param->getElementsByTagName( "name" )->item(0);
$newNode = $doc->createElement( "alias" );
$param->insertBefore($newNode,$name);
$newText = $doc->createTextNode($name->nodeValue);
$newNode->appendChild($newText);
}
$doc->saveXML();
}
And it works for me, thanks anyway.