How to use xml data in PHP

wailynnooJune 20, 20104min1400

www အောက်မှာ(in wamp server) folder တစ်ခုဆောက်ပြီး ဒီ xml code တွေကို notepad မှာ pase လုပ်ပြီး address.xml ဆိုတဲ့အမည်နဲ့ save လိုက်ပါ။
<?xml version=”1.0″ encoding=”utf-8″?>
<users>
<user>
<firstname>Sheila</firstname>
<surname>Green</surname>
<address>2 Good St</address>
<city>Campbelltown</city>
<country>Australia</country>
<contact>
<phone>1234 1234</phone>
<url>http://example.com</url>
<email>pamela@example.com</email>
</contact>
</user>
<user>
<firstname>Bruce</firstname>
<surname>Smith</surname>
<address>1 Yakka St</address>
<city>Meekatharra</city>
<country>Australia</country>
<contact>
<phone>4444 4444</phone>
<url>http://yakka.example.com</url>
<email>bruce@yakka.example.com</email>
</contact>
</user>
<user>
<firstname>Davo</firstname>
<surname>White</surname>
<address>The Only Way</address>
<city>Whitefall</city>
<country>Australia</country>
<contact>
<phone>8888 8888</phone>
<url>http://white.example.com</url>
<email>davo@white.example.com</email>
</contact>
</user>
<user>
<firstname>Shazza</firstname>
<surname>Green</surname>
<address>222 Great Western Hwy</address>
<city>Bathurst</city>
<country>Australia</country>
<contact>
<phone>6666 6666</phone>
<url>http://shazza.green.example.com</url>
<email>shazza@green.example.com</email>
</contact>
</user>
</users>

ပြီးရင် ဒီphp code တွေကို notepad မှာ pase လုပ်ပြီး index.php ဆိုပြီး save လုပ်လိုက်ပါ။

<?php

if( ! $xml = simplexml_load_file(‘address.xml’) )
{
echo ‘unable to load XML file’;
}
else
{
foreach( $xml as $user )
{
echo ‘Firstname: ‘.$user->firstname.'<br />’;
echo ‘Surname: ‘.$user->surname.'<br />’;
echo ‘Address: ‘.$user->address.'<br />’;
echo ‘City: ‘.$user->city.'<br />’;
echo ‘Country: ‘.$user->country.'<br />’;
echo ‘Email: ‘.$user->contact->phone.'<br />’;
echo ‘Email: ‘.$user->contact->url.'<br />’;
echo ‘Email: ‘.$user->contact->email.'<br /><br />’;
}
}
?>

ဒါကို browser မှာ run ရင်တော့ xml data ကို php မှာ ဘယ်လိုခေါ်ယူအသုံးချတယ်ဆိုတာသဘောပေါက်သွားမှာပါ။ ဒီ example မှာအဓိကကတော့ simplexml_load_file() ဆိုတဲ့ php ရဲ့ function ကိုခေါ်ယူအသုံးချခြင်းပါဘဲ။ file ကမဟုတ်ဘဲ string ကခေါ်ရင်တော့ simplexml_load_string() ကိုသုံးပါတယ်။
like this

<?php
$xml_string = ‘<?xml version=”1.0″ encoding=”iso-8859-1″?>
<users>
<user>
<firstname>Sheila</firstname>
<surname>Green</surname>
<address>2 Good St</address>
<city>Campbelltown</city>
<country>Australia</country>
<contact>
<phone>1234 1234</phone>
<url>http://example.com</url>
<email>pamela@example.com</email>
</contact>
</user>
</users>’;

if( ! $xml = simplexml_load_string( $xml_string ) )
{
echo ‘Unable to load XML string’;
}
else
{
echo ‘XML String loaded successfully’;
}

?>
Ref:phppro.com