我是 PHP 的新手,所以请放轻松;)
基本上我有一个 XML 文件,我正在尝试使用 PHP 将其转换为数组。我的 XML 文件supply.xml看起来有点像这样......
<Supplies>
<supply name="Pen">
<supplier name="Pen Island">http://domain.com/</supplier>
<quantity>2000</quantity>
<cost>100.00</cost>
</supply>
<supply name="Pencil">
<supplier name="Stationary World">http://domain.com/</supplier>
<quantity>5000</quantity>
<cost>115.30</cost>
</supply>
<supply name="Paper">
<supplier name="Stationary World">http://domain.com/</supplier>
<quantity>100</quantity>
<cost>10.50</cost>
</supply>
</Supplies>
我希望它转换成具有这种结构的数组...
Array (
[Pen] => Array (
[supplier] => Pen Island
[supplier_link] => http://domain.com/
[quantity] => 2000
[cost] => 100
)
[Pencil] => Array (
[supplier] => Stationary World
[supplier_link] => http://domain.com/
[quantity] => 5000
[cost] => 115.3
)
[Paper] => Array (
[supplier] => Stationary World
[supplier_link] => http://domain.com/
[quantity] => 100
[cost] => 10.5
)
)
我试过这个,但 PHP 不喜欢它......
<?php
$xml_supplies = simplexml_load_file("supplies.xml");
$supplies = array();
foreach ($xml_supplies->Supplies->supply as $supply) {
$supplies[(string)$supply['name']] = array(
"supplier" => (string)$supply->supplier['name'],
"supplier_link" => (string)$supply->supplier,
"quantity" => (int)$supply->quantity,
"cost" => (float)$supply->cost
)
}
print_r($supplies);
?>
我的理论是它会循环遍历每个供应元素并添加到$supplies数组中。
我花了将近一个小时试图让它工作,但我已经放弃了,需要一些帮助。谢谢。