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