dsrruefh12970 2016-11-11 20:48
浏览 40
已采纳

嵌套对象用php写入mysql

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.

  • 写回答

1条回答 默认 最新

  • doushenmao9036 2016-11-11 20:51
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条