简体   繁体   English

如何使用PHP检索以序列化XML字符串格式保存在MySQL数据库中的数据?

[英]How to retrieve the data which is saved in the format of serialized XML string in a MySQL database using PHP?

I have a field in a MySQL table which is saved in the format of serialized XML string using a SimpleXMLElement('<?xml version="1.0"?><XML-tree></XML-tree>') function. 我在MySQL表中有一个字段,该字段使用SimpleXMLElement('<?xml version="1.0"?><XML-tree></XML-tree>')函数以序列化XML字符串的格式保存。 How to retrieve the data to get the XML structure tree back to process the XML elements in PHP? 如何检索数据以获取XML结构树以处理PHP中的XML元素? thanks for your help 谢谢你的帮助

There are several ways. 有几种方法。 You need to first grab the mysql field which contains the xml data and use it this way for an example. 您首先需要获取包含xml数据的mysql字段,并以这种方式使用它作为示例。 When you say "retrieve the data to get the XML structure tree back" you need to literally get the field xml data with mysql_fetch_array or assoc and get it into a variable. 当您说“获取数据以返回XML结构树”时,您需要使用mysql_fetch_array或assoc从字面上获取字段xml数据,并将其放入变量中。 Lets say this was your xml data in MySQL DB: 可以说这是您在MySQL DB中的xml数据:

$xml_data_from_mysql = '<?xml version="1.0" encoding="UTF-8"?>
<resultset>
  <row>
    <name>Sami</name>
    <sex>M</sex>
  </row>
  <row>
    <name>Sami_F</name>
    <sex>F</sex>
  </row>
</resultset>';

//Use simplexml_load_string to process xml data
$simple  = simplexml_load_string($xml);
$array  = json_decode( json_encode($simple) , 1);
print_r($array);

**Output will be:**

Array
(
    [row] => Array
        (
            [0] => Array
                (
                    [name] => Sami
                    [sex] => M
                )
            [1] => Array
                (
                    [name] => Sami_F
                    [sex] => F
                )
        )
)

Once its converted to an array, you can manipulate the data however you want. 一旦将其转换为数组,就可以根据需要操作数据。 Or you can directly use php xml parser; 或者,您可以直接使用php xml解析器; I prefer to convert xml into an array for easy handling. 我更喜欢将xml转换为数组以便于处理。

You can use 您可以使用

simplexml_load_string

to create a SimpleXMLElement object from the string saved in the DB. 从数据库中保存的字符串创建SimpleXMLElement对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM