write and read XML


/ Published in: PHP
Save to your folder(s)

This is a simple example of how to read and write XML that includes reading attributes and nodes.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. $_SESSION['arrConfig'];
  4.  
  5.  
  6. $docConfigXML = new DOMDocument;
  7. $docConfigXML->preserveWhiteSpace = FALSE;
  8. $docConfigXML->load( 'resources/xml/config.xml' );
  9.  
  10. $_SESSION['arrConfig']['fax'] = trim($docConfigXML->getElementsByTagName("fax")->item(0)->getAttribute('value'));
  11. $_SESSION['arrConfig']['phone'] = trim($docConfigXML->getElementsByTagName("phone")->item(0)->nodeValue);
  12.  
  13. echo $_SESSION['arrConfig']['fax'];
  14. echo "<br />";
  15. echo $_SESSION['arrConfig']['phone'];
  16.  
  17. $strConfigXML = "";
  18.  
  19.  
  20. $fax = "702-555-1faxxx";
  21. $phone = '702-555-phone';
  22.  
  23. $strConfigXML =
  24. <<<END
  25. <?xml version="1.0" encoding="utf-8"?>
  26. <config>
  27. <fax value='$fax' />
  28. <phone>
  29. $phone
  30. </phone>
  31. </config>
  32. END;
  33.  
  34. $file = "resources/xml/config.xml";
  35.  
  36. writeFile($file,$strConfigXML);
  37.  
  38. function writeFile($file,$strFileContent)
  39. {
  40. $fh = fopen($file, 'w' ) or die ("can't create file");
  41. fwrite($fh, $strFileContent);
  42. fclose($fh);
  43. }
  44. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.