Unset the parser after calling xml_parser_free() to prevent memory leaks:
<?php
xml_parser_free($parser);
unset($parser);
?>
(PHP 4, PHP 5, PHP 7, PHP 8)
xml_parser_free — XML パーサを解放する
注意:
この関数を実行しても何も起こりません。PHP 8.0.0 より前のバージョンでは、この関数はリソースを閉じるのに使われていました。
指定した XML パーサ parser
を解放します。
パースが終了した際、
xml_parser_free() 関数を呼び出すのに加えて、
PHP 8.0.0 より前のバージョンでは
オブジェクトがパーサのリソースを参照している場合に、
メモリリークを避けるために parser
の参照を
明示的に unset することも必要になっています。
parser
成功した場合に true
を、失敗した場合に false
を返します。
Unset the parser after calling xml_parser_free() to prevent memory leaks:
<?php
xml_parser_free($parser);
unset($parser);
?>
If you try to free an XML parser while it is still parsing, strange things will happen - your script will "hang" and no output will be sent to the browser. Consider this pseudo-code example:
-------
...
if (!xml_parse($parser)) echo 'XML error';
xml_parser_free($parser);
...
function SomeCallbackWhichWasSetBefore(...)
{
global $parser;
...
if (some_error_happened) xml_parser_free($parser); //problem!
...
}
------
It would be logical that xml_parse would return false if the parser was freed while parsing, right? Wrong! Instead, everything hangs and no output will be sent out (no matter whether output buffering is on or not). It took me more than an hour to figure out why: you cannot free a parser handle that is currently parsing. A simple solution:
-------
$xml_error = false;
if (!xml_parse($parser))
echo 'XML error (directly from parser)';
else if ($xml_error)
echo 'XML error (from some callback function);
xml_parser_free($parser);
...
function SomeCallbackWhichWasSetBefore(...)
{
global $parser;
global $xml_error;
if ($xml_error)
return;
...
if (some_error_occured)
{
$xml_error = false;
return;
}
...
}
-------
If you use this solution you will have to check for $xml_error in every callback function. Essentially what you're doing is that, in case you want to stop parsing because of an error, you continue until xml_parse() is finished (without actually doing anything) and then free the parser and act on the error.
Of course the underlying problem is that you cannot stop a parser while it is parsing. There should be some function like xml_throw_error() or xml_parser_stop() or whatever, but unfortunately there isn't.
I found that with PHP 4.3.4RC1, if you don't call xml_parser_free() before your script ends, some sort of ugliness occurs with the webserver; i.e. the HTTP connection is closed. (The apache error_log says "exit signal Segmentation fault (11)".)
Usually PHP tends to clean up connections you don't explicitly close (e.g. database connections), but in this case apparently it doesn't.
Some web browsers (MSIE for one) do not actually show this problem, so you may not actually notice it. Opera 7.11 does show it, which is how I discovered it.
So don't forget to call xml_parser_free() ... always!