我有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)
);
答案 0 :(得分:0)
您可以使用simplexml_load_file
$file = 'test.xml';
if (file_exists($file)) {
$xml = simplexml_load_file($file);
print_r($xml);
} else {
exit('Failed to open '.$file);
}
答案 1 :(得分:0)
这是一组函数,它们将任何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;
}