我有来自Web服务的SOAP响应,并已将XML数据提取为SimpleXMLElement
。然后我遍历这个对象来提取我需要的各个字段并将它们保存到一个数组中,该数组成为SimpleXMLElement
个对象的数组。
我现在正试图将这些数据导出到MySQL数据库中,根据我的研究,这意味着将数组转换为字符串,然后使用mysql_query("INSERT INTO (whatever) VALUES (whatever)");
。我尝试了implode
和serialize
,但都没有工作,我收到错误:
Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'
这是我从SimpleXMLELement
创建的数组看起来像:
Array
(
[0] => Array
(
[uid] => SimpleXMLElement Object
(
[0] => WOS:000238186400009
)
[journal] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => source
)
)
[publication] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => item
)
[0] => Abundance of hedgehogs (Erinaceus europaeus) in relation to the density and distribution of badgers (Meles meles)
)
[year] => 2006
[author1] => SimpleXMLElement Object
(
[0] => Young, RP
)
[address] => SimpleXMLElement Object
(
[0] => Cent Sci Lab, Sand Hutton, Yorks, England
)
[author2] => SimpleXMLElement Object
(
[0] => Davison, J
)
[author3] => SimpleXMLElement Object
(
[0] => Trewby, ID
)
[citations] => SimpleXMLElement Object
(
[@attributes] => Array
(
[local_count] => 15
[coll_id] => WOS
)
)
) ... etc ...
)
有人可以帮助我将这些数据存入我的数据库吗?我是否需要将其更改为(还)另一种格式?
答案 0 :(得分:2)
您必须遍历数组以创建一个使用字符串而不是SimpleXMLElement实现的新数组,例如:
<?php
// your array (already built)
$arraySimpleXml = array(
"example1" => new SimpleXMLElement("<test>value</test>"),
"example2" => new SimpleXMLElement("<test>value2</test>")
);
// output array, to store in database
$result = array();
foreach($arraySimpleXml as $key => $simpleXml) {
$result[$key] = $simpleXml->asXML();
}
// gets your result as a string => you can now insert it into mysql
$dbInsertion = serialize($result);
&GT;
答案 1 :(得分:0)
所以我研究了如何将数据更改为标准数组而不是SimpleXMLElement
数组,以便我可以将其成功插入到MySQL数据库中。
当迭代SimpleXMLElement
对象以提取我需要的数据时,我将类型转换为String,以便现在我的数组具有格式(与上面相反):
Array
(
[0] => Array
(
[uid] => WOS:000238186400009
[journal] => JOURNAL OF ZOOLOGY
[publication] => Abundance of hedgehogs (Erinaceus europaeus) in relation to the density and distribution of badgers (Meles meles)
[year] => 2006
[author1] => Young, RP
[address] => Cent Sci Lab, Sand Hutton, Yorks, England
[author2] => Davison, J
[author3] => Trewby, ID
[citations] => 15
)
)
以为我会发布这个以防将来有人遇到类似的问题。为此,在迭代数据而不是:
时$uid = $record->UID;
我做了:
$uid = (string)$record->UID;
对于我需要的每个数据字段。这可确保数据存储为字符串,因此会删除SimpleXMLElement
格式。