Fabrizio Cocco Fabrizio Cocco - 28 days ago 7
MySQL Question

Nested Object write to mysql with php

I want to load an xml file, filter and put a few rows into the database. So far it works to load, parse to string, filter. But how can i access the second level of the objects properly?

object(SimpleXMLElement)#2 (2) {
["message_header"]=> object(SimpleXMLElement)#3 (1){
["@attributes"]=> array(6) {
["source"]=> string(10) "Alltron AG"
["message_type"]=> string(5) "price"
["document_version_date"]=> string(10) "12.07.2013"
["document_version"]=> string(4) "2.00"
["generation_date"]=> string(10) "11.11.2016"
["generation_time"]=> string(8) " 2:58:02" } }

["item"]=> array(85715) {
[0]=> object(SimpleXMLElement)#4 (2) {
["LITM"]=> string(4) "1289"
["price"]=> object(SimpleXMLElement)#85719 (4) {
["INPR"]=> string(5) "34.25"
["EXPR"]=> string(5) "31.71"
["VATR"]=> string(1) "8"
["ECPR"]=> string(2) "45" } }
[1]=> object(SimpleXMLElement)#5 (2) {
["LITM"]=> string(4) "1510"
and so on...


Now i start with load and parse:

$data = file_get_contents("../cache/PreisdatenV2.xml");
$xml = simplexml_load_string($data);


and the with the foreach:

foreach ($xml -> item as $row){
$litm = $row -> LITM;
$inpr = $row -> INPR;
$expr = $row -> EXPR;
$ecpr = $row -> ECPR;

if ($litm == 1289)

{
$sql = "INSERT INTO `preisdaten`(`litm`,`inpr`,`expr`,`ecpr`)" .
"VALUES ('$litm','$inpr','$expr','$ecpr')";
if ($conn->query($sql) === FALSE) {echo "Error: " . $sql . "
<br>" . $conn->error;}
};
};


It's working fine for $litm but not for the other values. How can i change the last to part to get the right values of the second level? Thank you very much for spending your time to help me.

Answer

The last three variables are subitems of price. So you need to change

$inpr = $row -> INPR;
$expr = $row -> EXPR;
$ecpr = $row -> ECPR;

to

$inpr = $row -> price -> INPR;
$expr = $row -> price -> EXPR;
$ecpr = $row -> price -> ECPR;