I want to save data from a xml file to my database, and below you can see my php code where i’ve tried to create an associative array to put the values into for later use. However, the actual SimpleXMLElement object is stored, not the just the pure value.
I have two questions here:
- How can I change my code so that the actual values (as numbers or strings) is stored instead of the SimpleXMLElement object?
- Is this a good way of storing the values for later storing with SQLLite (which I will use), or what other options do I have that works better?
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
producers.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>
...
outcome from 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...
change structure of the out put array: