How to modify an XML file using DOM

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!

Moderator: General Moderators

Post Reply
yele
Forum Newbie
Posts: 5
Joined: Tue Oct 21, 2008 1:28 pm

How to modify an XML file using DOM

Post by yele »

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,
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How to modify an XML file using DOM

Post by requinix »

SimpleXML makes the world go 'round... as long as you have PHP 5.

Code: Select all

$xml = new SimpleXML($file);
foreach ($xml->param as $p) {
    $alias = (string)$p->name;
    $p->appendChild("alias", $alias);
}
My DOM solution is bothersome, so if you can't do that then I'd try regular expressions:

Code: Select all

$xml = file_get_contents($file);
$xml = preg_replace("#<name>(.*?)</name>#s", "<alias>\$1</alias>\n\$0", $xml);
yele
Forum Newbie
Posts: 5
Joined: Tue Oct 21, 2008 1:28 pm

Re: How to modify an XML file using DOM

Post by yele »

tasairis wrote:SimpleXML makes the world go 'round... as long as you have PHP 5.

Code: Select all

$xml = new SimpleXML($file);
foreach ($xml->param as $p) {
    $alias = (string)$p->name;
    $p->appendChild("alias", $alias);
}
My DOM solution is bothersome, so if you can't do that then I'd try regular expressions:

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.
Post Reply