2017-06-06 43 views
-1

我需要关于将XML数据保存到MySQL数据库的帮助。这里是我的代码:如何在PHP中将XML子节点值保存到数据库

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

现在我想做的事是让<Description>标签和<URL>标签的值并将它们组合成为一个完整的URL,然后将它保存到MySQL数据库。

+0

您需要首先解析xml,使用'simplexml',解析完成后,使用pdo连接并插入 – Ghost

+0

谢谢生病请尝试您的建议先生,:-) – vince

回答

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 

然后使用PDOhttp://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(); 
} 
+0

谢谢你在这个@Sergey Kasatkin,生病尝试这一个。 :-) – vince

相关问题