Mat*_*hew 5 php xml mysql parsing
我被要求解析一个存储为XML文件的简单文件,然后将数据放入mysql数据库.
但是我完全不知道该怎么做,在网上查看之后给出的所有例子看起来都太复杂了我的问题或者没有正确的解决方案.XML文件如下所示:
<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>
Run Code Online (Sandbox Code Playgroud)
我试过看SimpleXML,我认为这是我必须走的方向,但我不知道.
任何帮助或指针都会很棒.
我个人喜欢正常的XMl格式,所以我更改了它,因为它更具可读性,但这是你如何使用它:
$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;
Run Code Online (Sandbox Code Playgroud)
处理部分:
$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/>';
}
Run Code Online (Sandbox Code Playgroud)
假设该文件被称为data.xml
$string = file_get_contents('data.xml')将整个文件读入$string.
$xml = new SimpleXMLElement($string);解析该字符串,并将其转换为类似于实际文档的对象树。所以如果那是文件 -
<root>
<b>
<c>first</c>
<c>second</c>
</b>
</root>
Run Code Online (Sandbox Code Playgroud)
SimpleXMLElement 对象的用法如下:
$xml->b // gets all children of b (c[0] and c[1])
print $xml->b->c[0] // gets the first c, will print "first"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24297 次 |
| 最近记录: |