使用DOM方法根据XML子节点值删除所在的父节点出错请教,谢谢
我的xml文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
- <books>
- <book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
- <book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
程序如下:
<?php
$doc = new DOMDocument();
$url="book.xml";
$xml_str=file_get_contents($url);
$doc->loadXML($xml_str);
$books = $doc->getElementsByTagName( "book" );
foreach( $books as $book )
{
$titles = $book->getElementsByTagName( "title" );
$title = $titles->item(0)->nodeValue;
if($title=="PHP Hacks")
{
$titles->parentNode->parentNode->removeChild($titles->parentNode);
}
}
?>
运行后提示错误:Fatal error: Call to a member function removeChild() on a non-object in E:\PHP MySQL\xampp\htdocs\xml1.php on line 14
请问下是为什么,谢谢
[解决办法]
错了,看这个
<?php $doc = new DOMDocument(); $url="book.xml"; $xml_str=file_get_contents($url); $doc->load($xml_str); $book = $doc->getElementsByTagName("book")[0]; foreach( $x in $book ) { if($x->tagName=='title'&&$x->nodeValue=="PHP Hacks"){ $book->removeChild($x); } }?>