phpfirstchild->data . “”;}
/*echo “从根结点遍历所有结点:”;foreach ($dom->documentelement->childnodes as $items) { //如果节点是一个元素(nodetype == 1)并且名字是item就继续循环 if ($items->nodetype == 1 && $items->nodename == “item”) { foreach ($items->childnodes as $titles) { //如果节点是一个元素,并且名字是title就打印它. if ($titles->nodetype == 1 && $titles->nodename == “title”) { print $titles->textcontent . ”
“; } } } } */
//使用xpath查询数据echo “使用xpath查询的title节点结果:”;$xpath = new domxpath($dom);$titles = $xpath->query(“/rss/channel/item/title”);foreach ($titles as $node){ echo $node->textcontent.””;}/*这样和使用getelementsbytagname()方法差不多,但是xpath要强大的多深入一点可能是这样:/rss/channel/item[position() = 1]/title 返回第一个item元素的所有 /rss/channel/item/title[@id = 23] 返回所有含有id属性并且值为23的title /rss/channel/&folder&/title 返回所有articles元素下面的title(译者注:&folder&代表目录深度)*/
//向dom中写入新数据$item = $dom->createelement(“item”);$title = $dom->createelement(“title”);$titletext = $dom->createtextnode(“title text”);$title->appendchild($titletext);$item->appendchild($title);$dom->documentelement->getelementsbytagname(channel)->item(0)->appendchild($item);
//从dom中删除节点//$dom->documentelement->removechild($dom->documentelement->getelementsbytagname(“channel”)->item(0));//或者使用xpath查询出节点再删除//$dom->documentelement->removechild($xpath->query(“/rss/channel”)->item(0));//$dom->save(“newfile.xml