开发者

PHP XML parsing: variable is reset every time it's used?

This function always outputs exactly one tab every time it calls the start() function. When it outputs the value of $tabs it's always 1 when displayed from start() and -1 when displayed from stop(). Why is $tabs not global?

$parser = xml_parser_create();
$tabs = 0;

function start($pars开发者_Go百科er, $element_name, $element_attrs) {
    $tabs = $tabs + 1;
    echo str_repeat("\t", $tabs).$element_name.": ";
}
function stop($parser, $element_name) {
    $tabs = $tabs - 1;
    echo "<br />";
}
function char($parser, $data) {
    echo $data;
}
xml_set_element_handler($parser, "start", "stop");
xml_set_character_data_handler($parser, "char");

$fp = fopen("$SignedRequest", "r");

while ($data = fread($fp, 4096)) {
    xml_parse($parser, $data, feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));
}

xml_parser_free($parser);


no, it is not, in PHP have to declare the global variables, like this:

function start($parser, $element_name, $element_attrs) {
global $tab;
    $tabs = $tabs + 1;
    echo str_repeat("\t", $tabs).$element_name.": ";
}

function stop($parser, $element_name) {
global $tab;
    $tabs = $tabs - 1;
    echo "<br />";
}


You forgot

global $tabs;

in your start() and stop() functions. PHP variables are "local" only, unless you explicitly mark them global.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜