使用php解析XML数据以放入mysql数据库 [英] Parsing XML data using php to put into mysql database

查看:91
本文介绍了使用php解析XML数据以放入mysql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求解析一个简单的文件,该文件存储为XML文件,然后将数据放入mysql数据库中.

I have been asked to parse a simple file which is stored as an XML file, the data is to be then put into a mysql database.

但是我绝对不知道该怎么办,在网上查看所有给出的示例后,问题似乎太复杂了,或者解决方案不正确. XML文件如下所示:

However I have absolutely no clue what to do and after looking online all the examples given seem either too complicated for my problem or not the right solution. The XML file looks like this:

<shop>
<products>
    <product id="1" name="Cornetto" price="1.20" description="Traditional Cornetto" />
    <product id="2" name="Smarties" price="1.00" description="Smarties Icecream" />
</products>

<stocks>
    <stock id="1" amount="242" price="pounds" />
    <stock id="2" amount="11" price="pounds" />
</stocks>

我尝试查看SimpleXML,我认为这是我必须走的方向,但是我不知道.

I've tried looking at SimpleXML and I think that's the direction I have to go but I just have no idea.

任何帮助或指针都很好.

Any help or pointers would be great.

推荐答案

我个人喜欢普通的XMl格式,所以我对其进行了更改,因为它的可读性更高,但这是您可以使用的方式:

I personally like the normal XMl formatting so I changed it since its a bit more readable but this is how you can use it:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<shop>
<products>
    <product>
        <id>1</id>
        <name>Cornetto</name>
        <price>1.20</price>
        <description>Traditional Cornetto</description>
    </product>
    <product>
        <id>2</id>
        <name>Smarties</name>
        <price>1.00</price>
        <description>Smarties Icecream</description>
    </product>
</products>
<stocks>
    <stock>
        <id>1</id>
        <amount>242</amount>
        <price>pounds</price>
    </stock>
    <stock>
        <id>2</id>
        <amount>11</amount>
        <price>pounds</price>
    </stock>
</stocks>
</shop>
XML;

处理部分:

$xml = new SimpleXMLElement($xmlstr);
echo 'single value: <br />';
echo $xml->products->product[0]->id; // get single value

echo '<br /><br />';

//Loop trough multiple products
echo 'multiple values: <br />';
foreach($xml->products->product as $product)
{
    echo $product->id.' - ';
    echo $product->name.' - ';
    echo $product->price.' - ';
    echo $product->description;
    echo '<br/>';
}

这篇关于使用php解析XML数据以放入mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆