我如何在数组中存储xml dom对象

时间:2014-03-11 07:03:11

标签: php xml dom

我想在数组中存储xml Dom对象,并使用数组索引

从数组中检索它们

例如

arrayoftags[index] = $this->dom->createElement("plist");
index++;

// and retrive back 

$dict = $this->dom->createElement("dict");
arrayoftags[index]->appendChild($dict);

/* some thing like that
 <plist>
   <dict>
   </dict>
 </plist>
*/

我做错了,请指导我正确的方向并提前致谢

2 个答案:

答案 0 :(得分:0)

请参考此代码,我认为这对您有帮助。

<!-- suppose this is book.xml file -->
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
 </book>
 <book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
 </book>
 <catalog>

//PHP file
$dom = new DOMDocument();
$dom->loadXml('book.xml');
$xpath = new DOMXpath($dom);
 $result = [];
 foreach ($xpath->evaluate('//book') as $book) {
 $result[] = [
'id' => $xpath->evaluate('string(@id)', $book),
'Author' => $xpath->evaluate('string(author)', $book),
'Title' => $xpath->evaluate('string(title)', $book),
'Genre' => $xpath->evaluate('string(genre)', $book),
'Price' => $xpath->evaluate('number(price)', $book),
'Publish Date' => $xpath->evaluate('string(publish_date)', $book),
'Description' => $xpath->evaluate('string(description)', $book)
];
}
var_dump($result);

答案 1 :(得分:0)

我不确定你为什么要使用数组。所以答案是更通用的。但是,您可以将XML节点存储在变量中,包括数组。

$dom = new DOMDocument();

$created = [];
$created['plist'] = $dom->appendChild($dom->createElement('plist'));

$created['dict'] = $dom->createElement('dict');
$created['plist']->appendChild($created['dict']);


echo $dom->saveXml();

输出:

<?xml version="1.0"?>
<plist><dict/></plist>

appendChild()返回附加的节点。因此可以直接在createElement()(或其他create *调用)上使用它,并将结果赋给变量。因此,如果父节点只存储在变量中,则示例将更清晰。

$dom = new DOMDocument();

$plist = $dom->appendChild($dom->createElement('plist'));
$plist->appendChild($dom->createElement('dict'));

echo $dom->saveXml();

现在DOM已经是一个数据结构了,您可以使用Xpath从中获取一些节点,为什么要将节点存储在第二个结构(数组)中?

$dom = new DOMDocument();

$plist = $dom->appendChild($dom->createElement('plist'));
$plist->appendChild($dom->createElement('dict'));

$xpath = new DOMXpath($dom);
foreach ($xpath->evaluate('//*') as $node) {
  var_dump($node->nodeName);
}

输出:

string(5) "plist"
string(4) "dict"