Posted By

donkeykong on 07/24/08


Tagged

attributes xml read write nodes getAttribute nodeValue


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jackkeller


write and read XML


 / Published in: PHP
 

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

  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  

You need to login to post a comment.