我想将数据从 xml 文件保存到我的数据库,在下面你可以看到我的 php 代码,我试图在其中创建一个关联数组以将值放入以供以后使用。但是,实际的 SimpleXMLElement 对象被存储,而不仅仅是纯值。
我在这里有两个问题:
- 如何更改我的代码以便存储实际值(作为数字或字符串)而不是 SimpleXMLElement 对象?
- 这是存储值以供以后使用 SQLLite(我将使用)存储的好方法,还是我有哪些其他选项效果更好?
php:
$theProducers = simplexml_load_file('sources/producers.xml');
$i = 0;
foreach ($theProducers->producer as $producer) {
$producers['id'][$i] = $producer->attributes();
$producers['name'][$i] = $producer->name;
$producers['address'][$i] = $producer->address;
$producers['zipcode'][$i] = $producer->zipcode;
$producers['town'][$i] = $producer->town;
$producers['url'][$i] = $producer->url;
$producers['imgurl'][$i] = $producer->imgurl;
$i += 1;
}
print_r($producers); // outcome below
生产者.xml:
<?xml version="1.0"?>
<producers>
<producer id="8">
<name>Emåmejeriet</name>
<address>Grenvägen 1-3</address>
<zipcode>577 39</zipcode>
<town>Hultsfred</town>
<url>http://www.emamejeriet.se</url>
<imgurl>http://172.16.206.1/~thajo/1DV449/laboration01/producenter/images/ema.png</imgurl>
</producer>
<producer>
...
print_r($producers) 的结果:
Array (
[id] => Array (
[0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 8 ) )
[1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 57 ) )
[2] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 45 ) )
[3] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 33 ) )
[4] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 16 ) )
[5] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 41 ) )
[6] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 38 ) )
[7] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 40 ) )
[8] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 56 ) ) )
[name] => Array (
[0] => SimpleXMLElement Object ( [0] => Emåmejeriet )
[1] => SimpleXMLElement Object ( [0] => Ölands Örtagård AB )
[2] => SimpleXMLElement Object ( [0] => Dövestads utegrisar & Gårdsbutik )
... and so on...