I have a text file generated by a device which provides me the data in this form:
Rajeet Singh|email@gmail.com|0123456789|Delhi
Abhishek|email2@gmail.com|0123456987|Pune
I want to extract the data from the text file and convert it into XML form as shown below:
<user>
<item0>
<name>Rajeet</name>
<email>email@gmail.com</email>
<mobile>0123654789</mobile>
<address>Delhi</address>
</item0>
<item1>
<name>Abhishek</name>
<email>email@gmail.com</email>
<mobile>0123654789</mobile>
<address>Pune</address>
</item1>
</user>
This is what I have done so far.
I have extracted the data from the text file and converted into an array.
$fh=fopen('file/dat.txt','r');
$xml = new SimpleXMLElement('<user></user>');
while($line=fgets($fh)){
$line_arr=explode('|',$line);
}
And converted a static valued array to xml like this:
$users_array = array(
array(
"name" => "Rajeet",
"email" => "email@gmail.com",
"mobile" => "0123654789",
"address" => "Delhi",
),
array(
"name" => "Abhishek",
"email" => "email@gmail.com",
"mobile" => "0123654789",
"address" => "Pune",
)
);
print_r($users_array);
//function defination to convert array to xml
function array_to_xml($array, &$xml_user_info) {
foreach($array as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_user_info->addChild("$key");
array_to_xml($value, $subnode);
}else{
$subnode = $xml_user_info->addChild("item$key");
array_to_xml($value, $subnode);
}
}else {
$xml_user_info->addChild("$key",htmlspecialchars("$value"));
}
}
}
//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><user></user>");
//function call to convert array to xml
array_to_xml($users_array,$xml_user_info);
//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xml');
//success and error message based on xml creation
if($xml_file){
echo 'XML file have been generated successfully.';
}else{
echo 'XML file generation error.';
}
?>
But I am not sure how to format the array I got from the Text file.
Any help will be highly appreciated.
Thanks