【发布时间】:2017-05-10 06:54:17
【问题描述】:
您好,我正在处理需要将 xml 转换为 csv 文件的操作
下面是我的xml文件格式。
<CatalogLine>
<Item>
<ItemID agencyRole="MasterProductNumber">
<ID>11802</ID>
</ItemID>
<ItemID agencyRole="Prefix_Number">
<ID>FOL</ID>
</ItemID>
<ItemID agencyRole="Stock_Number">
<ID>00374EA</ID>
</ItemID>
</Item>
<UOMCode>EA</UOMCode>
<ItemPrice>
<UnitPrice>
<Amount currencyID="USD">0</Amount>
<PerQuantity unitCode="EA">1</PerQuantity>
<Code>Catalog_List_Amount</Code>
</UnitPrice>
</ItemPrice>
<Note type="Page_Number">5</Note>
</CatalogLine>
500 多次相同。
所以我需要csv 中的所有数据,比如
MasterProductNumber Prefix_Number Stock_Number UOMCode Amount PerQuantity Code Page_Number
11802 FOL 00374EA EA 0 1 Catalog_List_Amount 5
下面的代码我试过了:
<?php
$filexml='ddsource.xml';
if (file_exists($filexml)) {
$xml = simplexml_load_file($filexml);
$i = 1; // Position counter
$values = []; // PHP array
// Writing column headers
$columns = array('MasterProductNumber','Prefix_Number','Stock_Number','UOMCode','Amount','PerQuantity','Code','Page_Number');
$fs = fopen('ddsource1.csv', 'w');
fputcsv($fs, $columns);
fclose($fs);
// Iterate through each <item> node
$node = $xml->xpath('//CatalogLine');
foreach ($node as $n) {
// Iterate through each child of <item> node
$child = $xml->xpath('//CatalogLine['.$i.']/*');
foreach ($child as $value) {
$values[] = $value;
}
// Write to CSV files (appending to column headers)
$fs = fopen('ddsource1.csv', 'a');
fputcsv($fs, $values);
fclose($fs);
$values = []; // Clean out array for next <item> (i.e., row)
$i++; // Move to next <item> (i.e., node position)
}
}
?>
但它只给主节点值: UOMCode - EA 注意 - 5
我需要所有的价值观。
请帮助我在哪里犯了错误。
【问题讨论】:
-
你有这个
XML还是一个例子? -
是有它的实际xml
-
希望我的解决方案能帮到你..
-
@SahilGulati 如果我需要从 xml 文件加载内容怎么办?
-
我已经更新了我的帖子,你可以检查 cmets.. 你可以像这样加载字符串
$string= file_get_contents("/path/to/file.txt");