PHP add data to XML file example

Source: Internet
Author: User
Tags xml file example

PHP adds data to the XML file
time: 2015-12-17-06:30:37 Source: Network
Reading: PHP adds data to an XML file

XML file: Stu.xml:

Copy CodeThe code is as follows: <?xml version= "1.0" encoding= "Utf-8"?>
<AllData>
<xueshengmen>
<xuesheng>
<name> Zhang San </name>
<yuwen>80</yuwen>
<shuxue>90</shuxue>
<yingyu>70</yingyu>
</xuesheng>
<xuesheng>
<name> John Doe </name>
<yuwen>60</yuwen>
<shuxue>90</shuxue>
<yingyu>75</yingyu>
</xuesheng>
</xueshengmen>
</AllData> above document Stu.xml provides some student data.
Now you need to add a Zongfen property to each Xuesheng node and its value equals the value of Yuwen+shuxue+yingyu.
As shown below:
Copy CodeThe code is as follows: <?xml version= "1.0" encoding= "Utf-8"?>
<AllData>
<xueshengmen>
<xuesheng>
<name> Zhang San </name>
<yuwen>80</yuwen>
<shuxue>90</shuxue>
<yingyu>70</yingyu>
<zongfen>240</zongfen>
</xuesheng>
<xuesheng>
<name> John Doe </name>
<yuwen>60</yuwen>
<shuxue>90</shuxue>
<yingyu>75</yingyu>
<zongfen>2225</zongfen>
</xuesheng>
</xueshengmen>
</AllData>

Using PHP to achieve:

Copy CodeThe code is as follows: <?php
$doc = new DOMDocument ();
$doc->load (' stu.xml ');
$students = $doc->getelementsbytagname ("Xuesheng");
foreach ($students as $stu) {
$yuwen = $stu->getelementsbytagname ("Yuwen")->item (0)->nodevalue;
$shuxue = $stu->getelementsbytagname ("Shuxue")->item (0)->nodevalue;
$yingyu = $stu->getelementsbytagname ("Yingyu")->item (0)->nodevalue;
$zongfen = $stu->getelementsbytagname ("Zongfen")->item (0)->nodevalue;
if ($zongfen) {
echo "Node already exists, no longer added!";
Continue
}
$zongfen = $yuwen + $shuxue + $yingyu;
$newNode = $doc->createelement ("Zongfen", $zongfen);
$stu->appendchild ($newNode);
}
$result = $doc->savexml (' stu.xml ');
?> related articles
    • PHP class DOMDocument for manipulating XML
    • PHP generates a simple XML file
    • Sample code Learning for PHP generated XML files

PHP add data to XML file example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.