如何使用php自动增加xml文件

时间:2012-02-14 19:04:36

标签: php xml

我正在尝试自动增加我的xml文件。我有一个表单,人们提交并将信息保存到xml文档中。我无法进行自动增量。数据保存,但id保持不变,即0

XML文档架构

<affiliates>

    <affiliate id="0">
        <FullName></FullName>
        <Company></Company>
        <Degree_Certificate></Degree_Certificate>
        <City></City>
        <StateProvidenceRegion></StateProvidenceRegion>
        <Phone></Phone>
        <Emailaddress></Emailaddress>
        <Descriptions></Descriptions>
    </affiliate>

<affiliates>

PHP代码:问题:

$root = $doc->createElement('affiliate', '');
$aff = count($root);
for ($i = 0; $i < $aff; $i++)
{
    $root->setAttribute('id', $i);
    $fullname = $doc->createElement('FullName', $fname.' '.$lname);
    $certdegree = $doc->createElement('Degree_Certificate', $degree);
    $Company = $doc->createElement('Company', $company);
    $Street = $doc->createElement('City', $address);
    $StateProvidenceRegion = $doc->createElement('StateProvidenceRegion', $state);
    $Phone = $doc->createElement('Phone', $phone);
    $EmailAddress = $doc->createElement('Emailaddress', $email);
    $Description = $doc->createElement('Descriptions', $message);
    $doc->appendChild($root);
    $root->appendChild($fullname);
    $root->appendChild($Company);
    $root->appendChild($certdegree);
    $root->appendChild($Street);
    $root->appendChild($StateProvidenceRegion);
    $root->appendChild($Phone);
    $root->appendChild($EmailAddress);
    $root->appendChild($Description);
    $doc->documentElement->appendChild($root);
}

请使用此代码帮助我。 PHP不是我的强项。我没有添加什么代码。

1 个答案:

答案 0 :(得分:0)

<?php
//Process form data here.

//Get the XML Document
$doc = new DOMDocument();
$doc->load("affiliates.xml"); //Load the existing XML here.

//Get the affiliates node here
$root = $doc->documentElement;

//Get the ID of this record here.
//If you know that no affiliate entries will ever be deleted, then you can use the total number of entries as the next increment value.
$totalAffiliates = $root->childNodes->length;

$node = $doc->createElement("affiliate");
$node->setAttribute("id", $totalAffiliates);
$node->appendChild($doc->createElement("FullName", $fname . ' ' . $lname));
$node->appendChild($doc->createElement("Degree_Certificate", $degree));
$node->appendChild($doc->createElement("Company", $company));
$node->appendChild($doc->createElement("City", $address));
$node->appendChild($doc->createElement("StateProvidenceRegion", $state));
$node->appendChild($doc->createElement("Phone", $phone));
$node->appendChild($doc->createElement("Emailaddress", $email));
$node->appendChild($doc->createElement("Descriptions", $message));

$root->appendChild($node);

//Write your XML back to the file.
?>

此代码应该可以满足您的需求。你需要在几个地方调整它,以适应你已有的。