-
- //Read xml
- $dom=new DOMDocument('1.0');
- $dom->load('data.xml');
- $em=$dom-> ;getElementsByTagName('videos');//Outermost node
- $em=$em->item(0);
- $items=$em->getElementsByTagName('video');//Node
- // If you don’t need to read and add it directly, just remove the following paragraph
- foreach($items as $a){
- foreach($a->attributes as $b){//$b->nodeValue; node attributes Value $b->nodeName;The name of the node attribute
- echo $b->nodeName;
- echo ":";
- echo $b->nodeValue;
- echo "
";
- }
- }
- //The following is to write a new line to xml
- $t=$dom->createElement('video');//
- $dom->save('data.xml');
- ?>
-
Copy code
The xml document at that time:
The following is the last change to modify the xml file:
-
- $doc = new DOMDocument();
- $doc->load('data.xml');
-
- //Find the videos node
- $root = $doc-> getElementsByTagName('videos');
-
- //The first videos node
- $root = $root->item(0);
-
- //Find the video node under the videos node
- $userid = $root-> getElementsByTagName('video');
-
- //Traverse all video nodes
- foreach ($userid as $rootdata)
- {
- //Traverse all attributes of each video node
- foreach ($rootdata->attributes as $attrib)
- {
- $attribName = $attrib->nodeName; //nodeName is the attribute name
- $attribValue = $attrib->nodeValue; //nodeValue is the attribute content
-
- //Find the node content with the attribute name ip
- if ( $attribName =='img')
- {
- //Find the node content whose attribute content is ip
- if ($attribValue =='1')
- {
- //Change the attribute to img and the img content to 1 to image ;
- $rootdata->setAttribute('img','image');
- $doc->save('data.xml');
- }
- }
- }
- }
- ?>
Copy code
Script Academy editor recommendation:
php class for reading xml
php xml document parsing function learning example
A piece of code for php to parse XML data
Several ways to read XML with PHP
Code for reading XML files using DOM class in php
Learn how to use PHP to operate XML class DOMDocument
|