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

报告相同问题?

悬赏问题

  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误