Home > Backend Development > PHP Tutorial > php add data to xml file

php add data to xml file

高洛峰
Release: 2016-10-10 10:57:56
Original
1030 people have browsed it

Introduction: PHP adds data to xml file

xml file: stu.xml:

Copy the code code as follows:

<?xml version="1.0" encoding="utf-8" ?>
<AllData>
<xueshengmen>
<xuesheng>
  <name>张三</name>
  <yuwen>80</yuwen>
  <shuxue>90</shuxue>
  <yingyu>70</yingyu>
</xuesheng>
<xuesheng>
  <name>李四</name>
  <yuwen>60</yuwen>
  <shuxue>90</shuxue>
  <yingyu>75</yingyu>
</xuesheng>
</xueshengmen>
</AllData>
Copy after login

The above file stu.xml provides some student data.
Now you need to add a zongfen attribute to each xuesheng node and its value is equal to the value of yuwen+shuxue+yingyu
as shown below:

Copy the code as follows:

<?xml version="1.0" encoding="utf-8" ?>
<AllData>
<xueshengmen>
<xuesheng>
  <name>张三</name>
  <yuwen>80</yuwen>
  <shuxue>90</shuxue>
  <yingyu>70</yingyu>
  <zongfen>240</zongfen>
</xuesheng>
<xuesheng>
  <name>李四</name>
  <yuwen>60</yuwen>
  <shuxue>90</shuxue>
  <yingyu>75</yingyu>
  <zongfen>2225</zongfen>
</xuesheng>
</xueshengmen>
</AllData>
Copy after login

Use PHP to implement:

Copy the code code 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 “节点已经存在了,不再添加!”;
   continue;
  }
  $zongfen = $yuwen+$shuxue+$yingyu;
  $newNode = $doc->createElement(“zongfen”,$zongfen);
  $stu->appendChild($newNode);
  }
 $result = $doc->saveXML(‘stu.xml’);
?>
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template