PHP add data to XML file for simple instance sharing

Source: Internet
Author: User
This article mainly introduces the PHP to add data to the XML file of a simple example, interested in a friend's reference, I hope to be helpful to everyone.

XML file: Stu.xml:

<?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>

The above file Stu.xml provides some *.

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:

<?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:

<?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 ');? >

Summary: The above is the entire content of this article, I hope to be able to help you learn.

Related Article

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.