我正在上传一个xml并试图将该数据转换为php数组,并将其存储在数据库中。我的问题是,当我得到空键内循环它自动转换成数组。但我只希望它是字符串。因为我得到数组,所以我很难把它存储在db。请帮我解决这个问题。
电流输出:
array(19) {
["EMP_NAME"]=>
string(12) "ABC"
["EMP_ADDRESS"]=>
string(1) "MUMBAI"
["DEPARTMENT"]=>
string(1) "IT"
["LOCATION"]=>
array(0) {
}
}
期望输出:
array(19) {
["EMP_NAME"]=>
string(12) "ABC"
["EMP_ADDRESS"]=>
string(1) "MUMBAI"
["DEPARTMENT"]=>
string(1) "IT"
["LOCATION"]=>
string(1) ""
}
这是我的php代码获取数据从xml和循环通过数组。
$xml = file_get_contents('uploads/data.xml');
$xml = simplexml_load_string($xml);
$xml_array = json_decode(json_encode((array) $xml), 1);
$data = ($xml_array);
foreach($data as $val){
//var_dump($val);
}
我试着修复它后得到。
<?php
function fixContent(&$val, $key = null) {
if (is_array($val)) {
if (!$val) $val = '';
else fix($val);
}
}
function fix(&$arr) {
array_walk($arr, 'fixContent');
array_walk_recursive($arr, 'fixContent');
}
$xml = "<?xml version='1.0'?>
<document>
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body></body>
</document>";
$xml = simplexml_load_string($xml);
$xml_array = json_decode(json_encode((array) $xml), 1);
fix($xml_array);
$data = $xml_array;
var_dump($data);
?>
输出:array(4) {
["title"]=>
string(11) "Forty What?"
["from"]=>
string(3) "Joe"
["to"]=>
string(4) "Jane"
["body"]=>
string(0) ""
}
演示:https://paiza.io/projects/qQC5pfvhGz_FniCIK6S_9g
泛型转换通常不是最佳解决方案。它们允许源程序控制输出——特别是当你使用诸如序列化SimpleXMLElement
实例之类的调试特性时。
从XML中读取数据并将其添加到结果中。这使您的代码可以控制输出。您可以更改键,验证和转换值,添加默认值,…
$xml = <<<'XML'
<EMP>
<EMP_NAME>ABC</EMP_NAME>
<EMP_ADDRESS>MUMBAI</EMP_ADDRESS>
<DEPARTMENT>IT</DEPARTMENT>
<LOCATION></LOCATION>
</EMP>
XML;
$employee = new SimpleXMLElement($xml);
$result = [
'EMP_NAME' => (string)$employee->EMP_NAME,
'EMP_ADDRESS' => (string)$employee->EMP_ADDRESS,
'DEPARTMENT' => (string)$employee->DEPARTMENT,
'LOCATION' => (string)$employee->LOCATION
];
var_dump($result);
输出:
array(4) {
["EMP_NAME"]=>
string(3) "ABC"
["EMP_ADDRESS"]=>
string(6) "MUMBAI"
["DEPARTMENT"]=>
string(2) "IT"
["LOCATION"]=>
string(0) ""
}
或使用DOM:
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$result = [
'EMP_NAME' => $xpath->evaluate('string(/EMP/EMP_NAME)'),
'EMP_ADDRESS' => $xpath->evaluate('string(/EMP/EMP_ADDRESS)'),
'DEPARTMENT' => $xpath->evaluate('string(/EMP/DEPARTMENT)'),
'LOCATION' => $xpath->evaluate('string(/EMP/LOCATION)')
];
var_dump($result);