【问题标题】:Insert xml into sql with sql with foreach?使用带有foreach的sql将xml插入sql?
【发布时间】:2018-02-08 12:11:57
【问题描述】:

首先,我有一个来自 unibet.com 的 xml 提要,如下所示:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<betOfferResponse>
    <events>
        <name>Red Star Belgrade - CSKA Moscow</name>
        <homeName>Red Star Belgrade</homeName>
        <awayName>CSKA Moscow</awayName>
        <start>2018-02-13T17:00Z</start>
        <group>Europa League</group>
        <type>ET_MATCH</type>
        <sport>FOOTBALL</sport>
        <state>NOT_STARTED</state>
        <liveBetOffers>true</liveBetOffers>
        <openForLiveBetting>false</openForLiveBetting>
        <id>1004394826</id>
        <groupId>2000051195</groupId>
        <path>
            <id>1000093190</id>
            <name>Football</name>
            <englishName>Football</englishName>
        </path>
        <path>
            <id>2000051195</id>
            <name>Europa League</name>
            <englishName>Europa League</englishName>
        </path>
    </events>
    <events>
        <name>FC Astana - Sporting Lisbon</name>
        <homeName>FC Astana</homeName>
        <awayName>Sporting Lisbon</awayName>
        <start>2018-02-15T16:00Z</start>
        <group>Europa League</group>
        <type>ET_MATCH</type>
        <sport>FOOTBALL</sport>
        <state>NOT_STARTED</state>
        <liveBetOffers>true</liveBetOffers>
        <openForLiveBetting>false</openForLiveBetting>
        <id>1004394832</id>
        <groupId>2000051195</groupId>
        <path>
            <id>1000093190</id>
            <name>Football</name>
            <englishName>Football</englishName>
        </path>
        <path>
            <id>2000051195</id>
            <name>Europa League</name>
            <englishName>Europa League</englishName>
        </path>
    </events>

但是当我使用我的脚本读取 xml 数据并将其放入我的数据库时,它不起作用,因为这些:

 <betOfferResponse>

但是当我创建自己的 xml 时只使用下面的数据,它就可以工作。但它不能循环文件并获取第二个条目等等..

这是我的 php 代码:

    <?php


$xml=simplexml_load_file("test.xml") or die("Error: Cannot create object");
$connection = mysqli_connect("localhost", "root", "password", "tipstr") or die ("ERROR: Cannot connect");

/* Assumes that the number of IDs = number of customers */
$size = sizeOf($xml->id);
$i = 0; //index

/* Add each customer to the database, See how we reference it as    $xml->ENTITY[INDEX] */
while($i != $size) 
{
    print_r($xml);
    echo $xml->id[$i]; //Test

    $sql = "INSERT INTO xf_nflj_sportsbook_event (event_id, category_id, user_id, username, title, description, event_status, date_create, date_open, date_close, date_settle, date_edit, event_timezone, wagers_placed, amount_staked, amount_paidout, likes, like_users, view_count, outcome_count, comment_count, thread_id, prefix_id, last_comment_date, limit_wagers_single_outcome) VALUES ('$xml->id',2,1,'tipstr', '$xml->name', '$xml->sport', 'open', 1517755596,1517755596,1517761200,1517761200,0,'Europe/London', 0, 0,0,0,0,0,0,0,0,0,0,0)";
    mysqli_query($connection, $sql) or die ("ERROR: " .mysqli_error($connection) . " (query was $sql)");

    $i++; //increment index
}


mysqli_close($connection);

我做错了什么?如何循环/foreach 插入查询,以便它可以获取整个文件而不仅仅是第一个文件,以及如何让它从 unibet 读取 xml?

编辑: 很抱歉没有添加我成功时使用的 xml。但这里是:

 <events>
        <name>Marseille - S.C. Braga</name>
        <homeName>Marseille</homeName>
        <awayName>S.C. Braga</awayName>
        <start>2018-02-15T18:00Z</start>
        <group>Europa League</group>
        <type>ET_MATCH</type>
        <sport>FOOTBALL</sport>
        <state>NOT_STARTED</state>
        <liveBetOffers>true</liveBetOffers>
        <openForLiveBetting>false</openForLiveBetting>
        <id>1004394835</id>
        <groupId>2000051195</groupId>
        <path>
            <id>1000093190</id>
            <name>Football</name>
            <englishName>Football</englishName>
        </path>
        <path>
            <id>2000051195</id>
            <name>Europa League</name>
            <englishName>Europa League</englishName>
        </path>
    </events>
     <betoffers>
        <id>2086105579</id>
        <eventId>1004044027</eventId>
        <closed>2018-05-16T18:45Z</closed>
        <live>false</live>
        <startingPrice>false</startingPrice>
        <criterion>
            <id>1001221607</id>
            <label>Winner</label>
        </criterion>
        <betOfferType>
            <id>4</id>
            <name>Winner</name>
        </betOfferType>
        <outcomes>
            <id>2307553711</id>
            <odds>15000</odds>
            <label>AC Milan</label>
            <type>OT_UNTYPED</type>
            <changedDate>2018-02-05T22:19:04Z</changedDate>
            <oddsFractional>14/1</oddsFractional>
            <oddsAmerican>1400</oddsAmerican>
        </outcomes>
        <outcomes>
            <id>2307553715</id>
            <odds>7000</odds>
            <label>Arsenal</label>
            <type>OT_UNTYPED</type>
            <changedDate>2018-02-05T22:19:04Z</changedDate>
            <oddsFractional>6/1</oddsFractional>
            <oddsAmerican>600</oddsAmerican>
        </outcomes>

我没有收到任何特殊错误,当我在 xml 中添加更多项目时,只有我写入的 php 错误。所以尝试检查控制台中的网络选项卡,但也没有。

【问题讨论】:

  • “它不起作用”不是问题描述。为什么它不起作用?你有错误吗?出乎意料的结果?
  • “但是当我创建自己的 xml 时只使用下面的数据” - 我很好奇你自己构建的 XML 会是什么样子,如果它真的与该代码一起工作的话?对于初学者:id 低了几个级别,所以我根本看不出$xml-&gt;id 将如何工作,除非您完全更改了 XML 结构。您还获取$xml-&gt;name$xml-&gt;sport,它们位于不同的级别。
  • 下面是一个正确遍历 XML 对象的示例:stackoverflow.com/questions/871422/…
  • MySQL 支持批量插入。这里不需要为每个插入执行语句。使用循环构建大型插入语句或文件,然后使用它来插入数据。 (速度更快)

标签: php mysql xml


【解决方案1】:

感谢 Nigel Ren 给了我正确的公式,这是所有缺失数据的正确答案..

现在我终于可以从 unibet 的 xml 中获取数据了 :)

 <?php


$xml=simplexml_load_file("xml url") or die("Error: Cannot create object");
$connection = mysqli_connect("localhost", "root", "password", "db_name") or die ("ERROR: Cannot connect");

/* Assumes that the number of IDs = number of customers */
$size = sizeOf($xml->id);
$i = 2; //index

/* Add each customer to the database, See how we reference it as    $xml->ENTITY[INDEX] */
while($i != $size) 
{
    print_r($xml);
    echo $xml->id[$i]; //Test
    foreach($xml->events as $event) //Extract the Array Values by using Foreach Loop
    {
    $sql = "INSERT INTO xf_nflj_sportsbook_event (event_id, category_id, user_id, username, title, description, event_status, date_create, date_open, date_close, date_settle, date_edit, event_timezone, wagers_placed, amount_staked, amount_paidout, likes, like_users, view_count, outcome_count, comment_count, thread_id, prefix_id, last_comment_date, limit_wagers_single_outcome) VALUES ('$event->id',2,1,'tipstr', '$event->name', '$event->sport', 'pending', 1517755596,1517755596,1517761200,1517761200,0,'Europe/London', 0, 0,0,0,0,0,0,0,0,0,0,0)";
    mysqli_query($connection, $sql) or die ("ERROR: " .mysqli_error($connection) . " (query was $sql)");

    $i++; //increment index
    }
}


mysqli_close($connection);

【讨论】:

  • 您的while 循环不需要,$i 也不需要。
【解决方案2】:

您应该更改循环以使其更容易...

<?php
$xml=simplexml_load_file("xml url") or die("Error: Cannot create object");
$connection = mysqli_connect("localhost", "root", "password", "db_name") or die ("ERROR: Cannot connect");

foreach ( $xml->events as $event )  {
    $sql = "INSERT INTO xf_nflj_sportsbook_event
                (event_id, category_id, user_id, username, title,
                description, event_status, date_create, date_open,
                date_close, date_settle, date_edit, event_timezone,
                wagers_placed, amount_staked, amount_paidout, likes,
                like_users, view_count, outcome_count, comment_count, thread_id,
                prefix_id, last_comment_date, limit_wagers_single_outcome)
        VALUES ('{$event->id}',2,1,'tipstr', '{$event->name}', '{$event->sport}',
                'open',
                1517755596,1517755596,1517761200,1517761200,0,'Europe/London',
                0, 0,0,0,0,0,0,0,0,0,0,0)";
     mysqli_query($connection, $sql) or die ("ERROR: " .mysqli_error($connection) . " (query was $sql)");
}

请注意,我已更改数据嵌入字符串的方式,因为每个元素现在都称为 $event 我已将它们更改为 {$event-&gt;id} 等。

您还应该查看准备好的语句,因为您可以准备此语句一次,然后对每行数据执行多次。

这不会产生任何输出,只是将数据从文件中插入到数据库中。

【讨论】:

  • 你几乎是正确的,只是错过了一个结束 } 和另一行,så 我将添加正确的解决方案作为答案:) 但如果不是你,我不会想到它出来:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多