开发者

Modify XML content with XML Parser PHP

I have a pretty large XML file. I am parsing it with XML Pars开发者_StackOverflow社区er using Php. XML parsing part is ok, i can read the data. However, i have no idea modifying a single tag's content. Should I read the whole data into a string and rewrite the file with modified one? Is there any other solutions? I dont want to use simplexml because of the size of the file.

For example, i would like to change Jack to another user's name.

Jack

Thanks..

So far:

$file = "5.xml";



function startElement($parser, $name, $attrs) 
{
//do something

}

function contents($parser, $data){
//do something

} 

function endElement($parser, $name) 
{
//do something
}


$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "contents"); 
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);


Since it's a large XML file, XMLParser is the correct tool.

If you want to change a tag's content, you need to save the current tag name in startElement and output different content in contents when you encounter the tag you want to modify.

startElement: $this->currentTag = $name;
contents: $this->currentTag == 'myspecialtag' ? print(md5($data)) : print($data);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜