【发布时间】:2012-12-03 14:50:43
【问题描述】:
这是我正在使用的示例 xml:
<contact id="43956">
<personal>
<name>
<first>J</first>
<middle>J</middle>
<last>J</last>
Some text...
</name>
<title>Manager</title>
<employer>National</employer>
<dob>1971-12-22</dob>
</personal>
</contact>
我得到了Some text...,但现在我需要我的代码来读取整个 xml 文档。它也没有读取 xml 中的值...正如您所知,我以前从未使用过 XMLReader。
这是我得到的:
Array ( [contact] => Array ( [id] => 43956 [value] => some sample value ) [first] => [middle] => [last] => [#text] => Some text... [name] => [title] => [employer] => [dob] => [personal] => )
这是我现在拥有的代码:
function xml2array($file, array $result = array()) {
$lastElementNodeType = '';
$xml = new XMLReader();
if(!$xml->open($file)) {
die("Failed to open input file");
}
while($xml->read()) {
switch ($xml->nodeType) {
case $xml::END_ELEMENT:
$lastElementNodeType = $xml->nodeType;
case $xml::TEXT:
$tag = $xml->name;
if($lastElementNodeType == 15) {
$result[$tag] = $xml->readString();
}
case $xml::ELEMENT:
$lastElementNodeType = $xml->nodeType;
$tag = $xml->name;
if($xml->hasAttributes) {
while($xml->moveToNextAttribute()) {
$result[$tag][$xml->name] = $xml->value;
}
}
}
}
print_r($result);
}
我想过让这个函数递归,但是当我尝试这样做时,它使数组变得非常混乱。
我有这个版本,但它仍然没有输出first中的J等:
function xml2assoc($xml) {
$tree = null;
while($xml->read())
switch ($xml->nodeType) {
case XMLReader::END_ELEMENT: return $tree;
case XMLReader::ELEMENT:
$node = array('tag' => $xml->name, 'value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
if($xml->hasAttributes)
while($xml->moveToNextAttribute())
$node['attributes'][$xml->name] = $xml->value;
$tree[] = $node;
break;
case XMLReader::TEXT:
case XMLReader::CDATA:
$tree .= $xml->value;
}
return $tree;
}
【问题讨论】:
-
你真的应该使用内置的SimpleXML 类,而不是那种......不需要的复制/粘贴的abomination。它建于世纪之交,当时很糟糕,现在更糟。
-
@Charles 我也使用了这段代码
$array = json_decode(json_encode((array)simplexml_load_string(file_get_contents($this->file))),1);'但它速度较慢,性能非常重要。它也没有包含我需要的文本。 -
您在问题中发布的所有大量代码,您无法提取文本值的位置(在 php 代码中)到底在哪里寻找?你可能不想在你的情况下使用
SimpleXML,而是XMLReader。 -
我刚刚编辑了我的问题。我正在使用
XMLReader,就像你建议的那样。现在我的问题是如何在到达下一个内部标签之前只抓取文本?