【问题标题】:How to save XML child nodes value to database in PHP如何在 PHP 中将 XML 子节点值保存到数据库
【发布时间】:2017-06-06 08:49:06
【问题描述】:

我需要有关将 XML 数据保存到 MySQL 数据库的帮助。这是我的代码:

    <?xml version="1.0" encoding="UTF-8"?><Response Code="200"><Description>http://sample.net</Description><URL>/Patient/PatientView.aspx?pid=642</URL></Response>

现在我想做的是获取&lt;Description&gt;标签和&lt;URL&gt;标签的值并将它们组合成一个完整的url然后保存到mysql数据库中。

【问题讨论】:

  • 你需要先解析xml,使用simplexml,解析完成后,使用pdo连接并插入
  • 谢谢你的建议,先生,:-)

标签: php mysql xml


【解决方案1】:

在这里查看问题How do you parse and process HTML/XML in PHP?

您可以使用 SimpleXML(参见http://php.net/manual/en/simplexml.examples-basic.php)进行解析

$xmlStr = '<?xml version="1.0" encoding="UTF-8"?><Response Code="200"><Description>http://sample.net</Description><URL>/Patient/PatientView.aspx?pid=642</URL></Response>';

$response = new SimpleXMLElement($xmlStr);

$url = (string) $response->Description . (string) $response->URL;

$url 将包含:

http://sample.net/Patient/PatientView.aspx?pid=642

然后使用PDO (http://php.net/manual/en/book.pdo.php) 将数据存入数据库:

try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $stmt = $dbh->prepare("INSERT INTO sample (url) VALUES (:url)");
    $stmt->bindParam(':url', $url);
    $stmt->execute();
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

【讨论】:

  • 谢谢@Sergey Kasatkin,我试试这个。 :-)
猜你喜欢
  • 2012-11-15
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多