PHP Reading and Writing XML

  • 2021-08-05 09:09:49
  • OfStack

What is XML?
XML is a data storage format. It does not define what data to hold, nor does it define the format of the data. XML simply defines the tags and the attributes of those tags. A well-formed XML tag looks like this:


<name>Jack Herrington</name>

DOM Read XML


<?php
  $doc = new DOMDocument();
  $doc->load( 'books.xml' );
 
  $books = $doc->getElementsByTagName( "book" );
  foreach( $books as $book )
  {
  $authors = $book->getElementsByTagName( "author" );
  $author = $authors->item(0)->nodeValue;
 
  $publishers = $book->getElementsByTagName( "publisher" );
  $publisher = $publishers->item(0)->nodeValue;
 
  $titles = $book->getElementsByTagName( "title" );
  $title = $titles->item(0)->nodeValue;
 
  echo "$title - $author - $publisher\n";
  }
  ?>

Writing XML with DOM


<?php
  $books = array();
  $books [] = array(
  'title' => 'PHP Hacks',
  'author' => 'Jack Herrington',
  );
  $doc = new DOMDocument(); // Create dom Object
  $doc->formatOutput = true;
 
  $r = $doc->createElement( "books" );// Create Label
  $doc->appendChild( $r );            // Will $r Tag, add to xml Format.
 
  foreach( $books as $book )
  {
      $b = $doc->createElement( "book" );        // Create Label
      $author = $doc->createElement( "author" );
      $author->appendChild($doc->createTextNode( $book['author'] ));  // Add content to tags
      $b->appendChild( $author );                // Set child labels Add parent tag
     
     
      $r->appendChild( $b );                    // Add to the parent tag!
      }
     
      echo $doc->saveXML();
  ?>

These are the two sections of reading and writing XML DOM code, friends understand, any questions can give me a message


Related articles: