XML with PHP

php
المحتويات:
- نموذج ملف XML
- إنشاء XML من خلال PHP
- إعادة تحميل XML و إضافة عناصر إلية
- عرض محتوى XML
- حذف بيانات من XML

– نموذج ملف XML

<?xml version="1.0" encoding="utf-8"?>
<root>
  <person id="1">
      <name>Hana</name>
      <age>20</age>
  </person>
  <person id="2">
      <name>Ramy</name>
      <age>32</age>
  </person>
</root>

– إنشاء XML من خلال PHP

$xml = new DOMDocument('1.0');
$root = $xml->createElement('root'); //create root item
$xml->appendChild($root);  //insert root item in xml

$person = $xml->createElement('person');  //create person item
$root->appendChild($person);  //insert person item under root item

$name = $xml->createElement('name'); //create name item
$person->appendChild($name);  //insert name item under person item

$name_txt = $xml->createTextNode('hana'); //create string value
$name->appendChild($name_txt); //insert string value under name item

$xml->formatOutput = true;
$xml->save('myfile.xml'); //save xml output in myfile.xml file

يتم إنشاء ملف myfile.xml و يحتوى على xml التالي

<?xml version="1.0" encoding="utf-8"?>
<root>
  <person>
     <name>hana</name>
  </person>
</root>

– تحميل ملف XML و إضافة عناصر إليه

$xml = new DOMDocument();

$xml->load('myfile.xml'); // load myfile.xml

$root = $xml->getElementsByTagName('root')->item(0); //select first root item 
//start to insert second person item
$person = $xml->createElement('person');
$root->appendChild($person);

$name = $xml->createElement('name');
$person->appendChild($name);

$name_txt = $xml->createTextNode('ramy');
$name->appendChild($name_txt);

$xml->formatOutput = true;
$xml->save('myfile.xml');

– حذف عنصر XML

$xml = new DOMDocument();

$xml->load('myfile.xml'); // load myfile.xml

$AllTags = $xml->documentElement; // get all elements

$GetItem = $AllTags->getElementsByTagName('person')->item(1);  //select person item

$AllTags->removeChild($GetItem);  //remove selected item

$xml->formatOutput = true;
$xml->save('myfile.xml');  // save changes

Leave a Reply