[英]convert xml data to php array
我有帶有原始數據的xml行列名,我需要將其轉換為所需的數組形式:
<RETS ReplyCode="0" ReplyText="Operation Success.">
<DELIMITER value="09"/>
<COLUMNS>
AcresNum
ADAFeaturesYN
AdditionalFeatures
</COLUMNS>
<DATA>
0.0000 0 Ceiling Fan,Granite Counters,Multiple Attics,Security System</DATA></RETS>
我需要將其轉換為數組形式,如下所示:
array( [0] => array( ['AcresNum'] => 0.0000 ,
['ADAFeaturesYN'] => 0),
[1] => array( ['AcresNum'] => 1.0000 ,
['ADAFeaturesYN'] => 1)
);
您可以使用simplexml_load_file
$file = 'test.xml';
if (file_exists($file)) {
$xml = simplexml_load_file($file);
print_r($xml);
} else {
exit('Failed to open '.$file);
}
這是一組函數,可以將任何XML遞歸轉換為數組,無論深度和復雜度如何。 包括標簽,屬性等,您可以對其進行命名...。請注意,所有屬性標簽都在數組中設置了@attributes作為鍵,但是可以是您想要的任何東西。 在你的情況下使用
$result=xmlstr_to_array($xmlstring);
它被轉換為數組,可以根據需要操作您的東西。
// load xml string
function xmlstr_to_array($xmlstr) {
$doc = new DOMDocument();
$doc->loadXML($xmlstr);
return domnode_to_array($doc->documentElement);
}
// convert nodes
function domnode_to_array($node) {
$output = array();
switch ($node->nodeType) {
case XML_CDATA_SECTION_NODE:
case XML_TEXT_NODE:
$output = trim($node->textContent);
break;
case XML_ELEMENT_NODE:
for ($i = 0, $m = $node->childNodes->length; $i < $m; $i++) {
$child = $node->childNodes->item($i);
$v = domnode_to_array($child);
if (isset($child->tagName)) {
$t = ConvertTypes($child->tagName);
if (!isset($output[$t])) {
$output[$t] = array();
}
$output[$t][] = $v;
} elseif ($v) {
$output = (string) $v;
}
}
if (is_array($output)) {
if ($node->attributes->length) {
$a = array();
foreach ($node->attributes as $attrName => $attrNode) {
$a[$attrName] = ConvertTypes($attrNode->value);
}
$output['@attributes'] = $a;
}
foreach ($output as $t => $v) {
if (is_array($v) && count($v) == 1 && $t != '@attributes') {
$output[$t] = $v[0];
}
}
}
break;
}
return $output;
}
//convert types
function ConvertTypes($org) {
if (is_numeric($org)) {
$val = floatval($org);
} else {
if ($org === 'true') {
$val = true;
} else if ($org === 'false') {
$val = false;
} else {
if ($org === '') {
$val = null;
} else {
$val = $org;
}
}
}
return $val;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.