note 80176 added to ref.simplexml
| From: | andrvm at osu1 dot php dot net | Date: | Wed, 02 Jan 2008 23:01:09 +0000 |
| Subject: | note 80176 added to ref.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-134669@lists.php.net to get a copy of this message | ||
<?php
/**
* Remove node/nodes xml with xpath
*
* @param SimpleXMLElement $xml
* @param string XPath $path
* @param string ('one'|'child'|'all') $multi
*
* Use:
*
* Example xml file - http://ru2.php.net/manual/ru/ref.simplexml.php
*
* $xml = simplexml_load_file($xmlfile);
*
* //1. remove only 1 node (without child nodes)
* // $path must return only 1 (unique) node without child nodes
* removeNode($xml, '//movie/rating[@type="thumbs"]');
*
* //2. remove 1 node (with 1 child nodes)
* // $path can return any nodes - will be removed only first node
* // with all child nodes
* removeNode($xml, '//characters', 'child')
*
* //3. remove all nodes (with child nodes)
* // $path can return any nodes - will be removed all
* // with child nodes
* removeNode($xml, '//rating', 'all')
*
* $xml->asXML($xmlfile);
*
*/
function removeNode($xml, $path, $multi='one')
{
$result = $xml->xpath($path);
# for wrong $path
if (!isset($result[0])) return false;
switch ($multi) {
case 'all':
$errlevel = error_reporting(E_ALL & ~E_WARNING);
foreach ($result as $r) unset ($r[0]);
error_reporting($errlevel);
return true;
case 'child':
unset($result[0][0]);
return true;
case 'one':
if (count($result[0]->children())==0 && count($result)==1) {
unset($result[0][0]);
return true;
}
default:
return false;
}
}
?>
p.s. after use (if deleted all nodes):
<?php
function trimXml($xmlfile)
{
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
if (!$dom->load($xmlfile)) return false;
$dom->formatOutput = true;
if (!$dom->save($xmlfile)) return false;
return true;
}
?>
----
Server IP: 195.54.192.44
Probable Submitter: 213.85.169.59
----
Manual Page -- http://www.php.net/manual/en/ref.simplexml.php
Edit -- https://master.php.net/note/edit/80176
Del: integrated -- https://master.php.net/note/delete/80176/integrated
Del: useless -- https://master.php.net/note/delete/80176/useless
Del: bad code -- https://master.php.net/note/delete/80176/bad+code
Del: spam -- https://master.php.net/note/delete/80176/spam
Del: non-english -- https://master.php.net/note/delete/80176/non-english
Del: in docs -- https://master.php.net/note/delete/80176/in+docs
Del: other reasons-- https://master.php.net/note/delete/80176
Reject -- https://master.php.net/note/reject/80176
Search -- https://master.php.net/manage/user-notes.php