How to update XML file through web form using PHP: form name issue
I have done some searching on tis but cannot seem to find any easy way or other examples on the subject (I am new to PHP, XML as of a couple of months ago so bear with me :) ).
- I have an XML file populated with useable data
- I need to be able to load the whole XML file into a form, each child node loading into its own form field
- I want to modify the various fields
- and then save everything back to the same XML file, using PHP to parse the data
PROBLEM : how to label the "names" in the form fields so I know how to populate the proper child nodes. XML file looks like:
<band id="1">
<group>Guns N Roses</group>
<member>Duff</member>
</band>
<band id="2">
<group>Iron Maiden</group>
<member>Paul</member>
</band>
To update this through a web form I thought it best to have the name attribute in the INPUT field the same as the child node name.... but then I have would have 2 x groups and 2 members.
Should I somehow append the attribute to the end of the name s开发者_C百科uch that
<input name=group.1 value=$group.1>
<input name=group.1 value=$group.2>
(where $group.1 and $group.2 can be found using PHP DOM)
and then I have a unique name/value pair in the php $_POST array to use to update the XML file through DOM.
It all just seems very hackish and clunky, and I wonder if there is a more graceful way to do all of this. Again, very new to this... maybe there is already some obvious way to do this that I am completely missing.
Thanks for any help guys
Mr. B
First of all, your "XML" is not valid XML. It needs to have a root element that wraps all the content. Right now, you lack this root element because at the top level you have more than one element (......).
So correct this by wrapping your whole string into one other element:
$xml = "<root>$xml</root>";
Then load it in a DOMDocument element, and traverse and loop through it with DOMXPath or in a simpleXML object (which probably is quicker to code, not sure about performance).
edit: how to name the form elements for an easy update:
<input name="band[1][group]" value="$group1">
<input name="band[1][member]" value="$member1" />
<input name="band[2][group]" value="$group1">
<input name="band[2][member]" value="$member1" />
After you send the form via post, you can traverse all inputs doing a foreach
over $_POST['band']
array:
if (count($_POST) > 0)
{
if (is_array($_POST['band'])
{
foreach ($_POST['band'] as $id => $band)
{
echo "Band $id has group ".$band['group']." and member ".$band['member']."<br />\n";
}
}
}
精彩评论