Home>Article>Backend Development> Detailed explanation of the steps for php to parse xml and generate sql statements
This time I will bring you a detailed explanation of the steps for php to parse xml and generate sql statements. What are theprecautionsfor php to parse xml and generate sql statements. The following is a practical case, let's take a look.
There are many ways for PHP to parse XML. There are a lot of them in the documentation. Just search for them.
I encountered a requirement today: extract the node attributes from a certain xml, and then update the fields in a certain table of the database.
Idea:
Parse the XML and get all the node attributes-> Loop the node collection and get the corresponding attributes-> Splice the sql string and store it in an array –> Convert the array to a string and save it in a file
Xpath is used here. Two problems were encountered during the process of writing the code:
1. The historical path of xml The file cannot be loaded when the attribute is D:\xx\..., just change it to "/" (the delimiter under Linux)
2. Get the attributes of a node, use ::attributes, and the editor will There are constant red prompts. I found the document for a long time, and finally used ->getAttribute() (I guess, because it is too strange, it supports ->previousSibling and ->nodeValue). According to the DOMElement:: on the document getAttribute reported an error directly..
The following is the sample code:
xml 转换为 sql load($xml); $xpath = new DOMXPath($doc); $query = "//i"; $entries = $xpath->query($query); $len = $entries->length; echo "总共找到:".$len."个节点
"; $arr = array(); $idx = 0; while ($idx < $len) { $nodeItem = $entries->item($idx); $id = $nodeItem->getAttribute("i"); $name = $nodeItem->getAttribute("n"); $inf = $nodeItem->getAttribute("inf"); // echo "".$id.'--'.$name.'--'.$inf."
"; $idx++; array_push($arr, "update dress_item t SET t.s_name='".$name."',t.s_intro='".$inf."' WHERE t.n_doid=".$id.";"); } $dir = "d:/sql/"; if (!is_dir($dir)) { mkdir($dir); } file_put_contents("d:/sql/dress_item.sql", implode("\n\r", $arr)); echo "生成完毕!"; ?>
Because the data is generated from the database table, the number of nodes found That is the total number of records in the table. After generation, you can take a look to see if the content is correct, and then execute the sql script to achieve the purpose.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
PHP class reflection implementation dependencies Detailed explanation of injection steps
The above is the detailed content of Detailed explanation of the steps for php to parse xml and generate sql statements. For more information, please follow other related articles on the PHP Chinese website!