gpt4 book ai didi

php - 如何使用 PHP 将已解析的 XML 传递到 mySQL 数据库中?

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:30 24 4
gpt4 key购买 nike

我有一个本地服务器,我在其中接收 xml 文件。 xml 文件收到得很好,但我对如何将 XML 文件传递​​到我的数据库有疑问。

我检索 xml 文件就这么简单:

$xml_post = file_get_contents('php://input');

我收到的 xml 文件如下所示:

<city>
<id>1081</id>
<name>athens</name>
<country>Greece</country>
<info>etc etc etc</info>
</city>

我已经使用 phpmyadmin 手动创建了一个具有完全相同节点的数据库,因此我可以正确保存所有内容。

现在我想用 mysql_query 将我得到的内容插入到数据库中。像这样:

mysql_query("INSERT INTO cities (id, city ,country , info)
VALUES (4 , 'athens' , 'greece' , 'etc etc etc'");

但是我存储了我的 xml 以将它们用作上述语句中的值的变量是哪些?我如何解析我必须将所有节点存储在变量中然后将它们正确传递到数据库的 xml 文件?

最佳答案

尝试使用 simplexml_load_string()

示例用法:

<?php
$xml = '<city>
<id>1081</id>
<name>athens</name>
<country>Greece</country>
<info>etc etc etc</info>
</city>
';

$xml = simplexml_load_string($xml);
//1081
echo $xml->id;
//athens
echo $xml->name;
?>

如果您的 XML 中有多个节点,每个节点将是一个对象数组:

$xml = '
<citys>
<city>
<id>1081</id>
<name>athens</name>
<country>Greece</country>
<info>etc etc etc</info>
</city>
<city>
<id>1082</id>
<name>somwhere else</name>
<country>Spain</country>
<info>etc etc etc</info>
</city>

</citys>
';

$xml = simplexml_load_string($xml);
//print_r($xml);

foreach($xml->city as $val){
echo $val->name;
}

//or
echo $xml->city[0]->name;
//athens
echo $xml->city[1]->name;

关于php - 如何使用 PHP 将已解析的 XML 传递到 mySQL 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14326845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com