我正在处理这些数据:
name,address_one,address_two,address_postcode
Bob,1 A Street,A town,AA11AA
Andy,92 Church St,Manchester,M20 3JN
Sarah,893 London Road,Enfield,EN3 9HB
Freda,67 Green Close,Newcastle,Nw5 2ED
这是一个格式良好的 .csv 文件。我需要能够解析它,然后将其转换为多维 PHP 数组,以便将其格式化为 XML。
一旦成功,我的阵列可能如下所示:
Array
(
['name']=> Bob
[0] => Array
(
[address] => Array
(
[one] => 1 A Street
[two] => A town
[postcode] => WC2 9GH
)
)
['name']=> Andy
[1] => Array
(
[address] => Array
(
[one] => 92 Chuch St
[two] => Manchester
[postcode] => M20 3JN
)
)
... omitted
)
然后,我会将其转换为 XML,例如:
<?xml version="1.0"?>
<root>
<name>Bob</name>
<address>
<one>1 A Street</one>
<two>A town</two>
<postcode>AA11AA</postcode>
</address>
<name>Andy</name>
<address>
<one>92 Chuch St</one>
<two>Manchester</two>
<postcode>M20 3JN</postcode>
</address>
...omitted
</root>
我越来越接近这段代码:
public function parseFile($fileIn)
{
if (($handle = fopen("$fileIn", "r")) !== FALSE)
{
$header = NULL;
while (($row = fgetcsv($handle, 1000, ',')) !== FALSE)
{
if(!$header)
{
$header = $row;
foreach($header as $k => $v)
{
if($x = strpos("$v", '_'))
{
$child = substr("$v", $x+1);
array_push($header, $child);
}
}
} else {
$data[] = array_combine($header, $row);
}
}
print_r($data);
fclose($handle);
} else {
throw new Exception('Unable to open the file!');
}
} // parseFile
但看来我的参数不同步。
Warning: array_combine(): Both parameters should have an equal number of elements in
和
var_dump($header);
揭示:
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
如果我倒带一点:
$header = NULL;
while (($row = fgetcsv($handle, 1000, ',')) !== FALSE)
{
if(!$header) $header = $row;
else $data[] = array_combine($header, $row);
}
print_r($data);
我得到:
Array
(
[0] => Array
(
[name] => Bob
[address_one] => 1 A Street
[address_two] => A town
[address_postcode] => AA11AA
)
[1] => Array
(
[name] => Andy
[address_one] => 92 Church St
[address_two] => Manchester
[address_postcode] => M20 3JN
)
这很接近,但我需要能够将.csv文件的标题(在字符串'_'上)拆分为父子节点(考虑XML而不是数组)。
例如,address_one 将变为
Array
(
[0] => Array
(
[address] => Array
(
[one] => 1 A Street
)
)
)
其中一个是地址的孩子。同样对于 csv 文件中包含下划线的所有其他标题。没有下划线的标题只是像往常一样映射到值。
你能帮助我吗?