2017-06-06 42 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

相關問題