A simple example of PHP adding data to an XML file _php instance

Source: Internet
Author: User

XML file: Stu.xml:

<?xml version= "1.0" encoding= "Utf-8"?>
<AllData>
<xueshengmen>
<xuesheng>
 <name> John </name>
 <yuwen>80</yuwen>
 <shuxue>90</shuxue>
 <yingyu>70</yingyu>
</xuesheng>
<xuesheng>
 <name> Dick </name>
 <yuwen>60</yuwen>
 <shuxue>90</shuxue>
 <yingyu>75</yingyu>
</xuesheng>
</xueshengmen>
</AllData>

The above file Stu.xml provides some student data.

Now you need to add a Zongfen attribute to each Xuesheng node and its value equals Yuwen+shuxue+yingyu value

As shown below:

<?xml version= "1.0" encoding= "Utf-8"?>
<AllData>
<xueshengmen>
<xuesheng>
 <name> John </name>
 <yuwen>80</yuwen>
 <shuxue>90</shuxue>
 <yingyu>70</yingyu>
 <zongfen>240</zongfen>
</xuesheng>
<xuesheng >
 <name> Dick </name>
 <yuwen>60</yuwen>
 <shuxue>90</shuxue>
 <yingyu>75</yingyu>
 <zongfen>2225</zongfen>
</xuesheng>
</xueshengmen>
</AllData>

Use PHP to implement:

<?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 add! ";
  Continue;
 }
 $zongfen = $yuwen + $shuxue + $yingyu;
 $newNode = $doc->createelement ("Zongfen", $zongfen);
 $stu->appendchild ($newNode);
 }
 $result = $doc->savexml (' stu.xml ');
? >

The above PHP to add data to the XML file is a simple example of the small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.