Page 1 of 1

edit an xml that uses key entries

Posted: Mon Dec 06, 2010 1:11 am
by jdetmold
hope someone can point me in the right direction i am trying to use php to edit an xml file and have been able to do that just fine

however the file i now need to edit looks like this

XML File:

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<dict>
	<key>users</key>
	<array>
		<dict>
			<key>Username</key>
			<string>joe</string>
			<key>Email</key>
			<string>joe@hotmail.com</string>
			<key>Password</key>
			<string>this-is-joes-password</string>
		</dict>
	</array>
</dict>
I am unable to figure out how to edit only joe's email address and leave the rest

the code i would normally use to edit an xml file would look like this:

Code: Select all

<?php
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('file.xml');
$element = $xml->getElementsByTagName('item')->item(0);
$name = $element->getElementsByTagName('name')->item(0);

$name->nodeValue = 'new name';

$element->replaceChild($name, $name);


thanks to anyone who can help!

-Jeff

Re: edit an xml that uses key entries

Posted: Mon Dec 06, 2010 2:23 am
by requinix
That's really bad XML. Can you change it?

Re: edit an xml that uses key entries

Posted: Mon Dec 06, 2010 8:36 am
by jdetmold
no i would if i could but it's to configure a hardware device :( the data wouldnt really be email it would be ip addresses etc.
it's been driving me nuts!

Re: edit an xml that uses key entries

Posted: Mon Dec 06, 2010 11:14 am
by Weirdan

Code: Select all

<?php
$xml = <<<EOM
<?xml version="1.0" encoding="UTF-8"?>
<dict>
        <key>users</key>
        <array>
                <dict>
                        <key>Username</key>
                        <string>joe</string>
                        <key>Email</key>
                        <string>joe@hotmail.com</string>
                        <key>Password</key>
                        <string>this-is-joes-password</string>
                </dict>
        </array>
</dict>
EOM;

$xml = simplexml_load_string($xml);

$node = $xml->xpath('/dict/array[preceding-sibling::key[text()="users"]][1]/dict');

$node[0]->string[findEltByKey($node[0], 'Email')] = "joe@gmail.com";

function findEltByKey($node, $key) {
    $i = 0;
    foreach ($node as $elt) {
        if ($elt->getName() == 'key') {
            if (trim((string) $elt) == $key) {
                return $i; 
            }   
            $i++;
        }   
    }   
    return false;
}
var_dump($xml->asXML());
It's rather convoluted due to the less-then-ideal format you have and SimpleXML's limitations, but seems to work.