目前我有一个从XML表中提取信息的代码,问题是我无法按照自己的意愿显示信息。
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<ProductData version="2.0">
<Product>
<code>111111</code>
<name>The Name</name>
<brand>The Brand</brand>
<quantity>
<store1>5</store1>
<store2>4</store2>
</quantity>
</Product>
<Product>
<code>222222</code>
<name>The Name</name>
<brand>The Brand</brand>
<quantity>
<store1>6</store1>
<store2>4</store2>
</quantity>
</Product>
</ProductData>
的index.php
<?php
if (file_exists('demo.xml')) {
$codes = [];
$store1 = [];
$xml = simplexml_load_file('demo.xml');
foreach($xml->Product as $i => $product) {
$codes[] = $product->code;
$store1[] = $product->quantity->store1;
}
echo implode($codes,',');
echo "<br>";
echo implode($store1,',');
} else { exit('Error en archivo!'); }
?>
结果:
111111,222222
5,6
我需要什么:
╔═════════════╦══════════╦══════════╗
║ Code ║ Store 1 ║ Store 2 ║
╠═════════════╬══════════╬══════════╣
║111111 ║ 5 ║ 4 ║
║222222 ║ 6 ║ 4 ║
╚═════════════╩══════════╩══════════╝
它可以显示在如上所示的表格中,也可以只显示在逗号分隔的值中,以便稍后处理...
111111,5,4
222222,6,4
...
任何人都可以帮助我吗?谢谢!
答案 0 :(得分:2)
如果更改循环中构建数据的方式,则将行中的所有数据存储到数组的一个元素中,而不是存储在不同的数组中。然后你可以一次将这个替代数组内插()一行......
if (file_exists('demo.xml')) {
$data = [];
$xml = simplexml_load_file('demo.xml');
foreach($xml->Product as $i => $product) {
$data[] = [(string)$product->code
,(string)$product->quantity->store1
,(string)$product->quantity->store2
];
}
foreach ( $data as $line ) {
echo implode(",",$line).PHP_EOL;
}
} else { exit('Error en archivo!'); }
输出......
111111,5,4
222222,6,4
答案 1 :(得分:1)
您可以将每个“产品”数据存储在一个数组中。
$xml = simplexml_load_file('demo.xml');
$codes = [];
foreach($xml->Product as $i => $product) {
$data = [];
$data[] = (string)$product->code;
$data[] = (string)$product->quantity->store1;
$data[] = (string)$product->quantity->store2;
$codes[] = $data;
}
foreach ($codes as $code) {
echo implode(',', $code) . '<br>';
}
输出:
111111,5,4
222222,6,4
如果你想要一张桌子:
echo "<pre>";
echo "╔═════════════╦══════════╦══════════╗"."<br>";
echo "║ Code ║ Store 1 ║ Store 2 ║"."<br>";
echo "╠═════════════╬══════════╬══════════╣"."<br>";
foreach ($codes as $code) {
echo "║";
echo sprintf("%12s ║", $code[0]);
echo sprintf("%9s ║", $code[1]);
echo sprintf("%9s ║", $code[2]);
echo "<br>";
}
echo "╚═════════════╩══════════╩══════════╝"."<br>";
echo "</pre>";
输出:
╔═════════════╦══════════╦══════════╗
║ Code ║ Store 1 ║ Store 2 ║
╠═════════════╬══════════╬══════════╣
║ 111111 ║ 5 ║ 4 ║
║ 222222 ║ 6 ║ 4 ║
╚═════════════╩══════════╩══════════╝
答案 2 :(得分:0)
<?php
if (file_exists('demo.xml')) {
$xml = simplexml_load_file('demo.xml');
$str = '';
foreach($xml->Product as $i => $product) {
$str .= "<tr><td>{$product->code}</td><td>{$product->quantity->store1}</td><td>{$product->quantity->store2}</td></tr>\n";
}
echo <<<END
<table style="width:100%">
{$str}
</table>
END;
} else { exit('Error en archivo!'); }
?>
给你:
<table style="width:100%">
<tr><td>111111</td><td>5</td><td>4</td></tr>
<tr><td>222222</td><td>6</td><td>4</td></tr>
</table>