我有一个由设备生成的文本文件,它以这种形式提供数据:
Rajeet Singh|email@gmail.com|0123456789|Delhi
Abhishek|email2@gmail.com|0123456987|Pune
我想从文本文件中提取数据并将其转换为XML格式,如下所示:
<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>
这是我到目前为止所做的。
我从文本文件中提取了数据并转换为数组。
$fh=fopen('file/dat.txt','r');
$xml = new SimpleXMLElement('<user></user>');
while($line=fgets($fh)){
$line_arr=explode('|',$line);
}
并将静态值数组转换为xml,如下所示:
$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.';
}
?>
但我不知道如何格式化我从Text文件中获得的数组 任何帮助将受到高度赞赏。 感谢
答案 0 :(得分:0)
例如,您可以写如下。
Text file
修改强>
如果要从$string = <<<EOM
Rajeet Singh|email@gmail.com|0123456789|Delhi
Abhishek|email2@gmail.com|0123456987|Pune
EOM;
$tags = ['name','email','mobile','address'];
$users_array = array_map(function($n) use($tags){
$elements = explode('|', $n);
return array_combine($tags, $elements);
},explode(PHP_EOL, $string));
var_dump($users_array);
格式化数组。
array(2) {
[0] =>
array(4) {
'name' =>
string(12) "Rajeet Singh"
'email' =>
string(15) "email@gmail.com"
'mobile' =>
string(10) "0123456789"
'address' =>
string(5) "Delhi"
}
[1] =>
array(4) {
'name' =>
string(8) "Abhishek"
'email' =>
string(16) "email2@gmail.com"
'mobile' =>
string(10) "0123456987"
'address' =>
string(4) "Pune"
}
}
结果...
Floating notifications