dongyi0210 2011-02-21 04:59
浏览 91

simpleXML无法正确保存XML文件

I wrote an HTTP request that mobile devices send their respective tokens to the server, an this code on the server checks a XML file if the token was already registered. If so, it does nothing, if not, it adds the new token to the XML.

When when saving (maybe because there are many people trying to access at the same time), the xml gets truncated, like this:

<root> <token> 123456 </token> <token> 234567 </token> <token> 345678 </to

What shall be happening?

The code is something like this:

    if( !ini_get('safe_mode') ){
        set_time_limit(0);
    } 

    if (file_exists("tokens.xml")) 
    {
        $xml = simplexml_load_file("tokens.xml");       

        if ($xml)
        {
            $found = false;

            foreach($xml->children() as $child)
            {
                if ($_POST['token'] == $child) 
                {
                    $found = true;
                    break;
                }
            }
            if ($found)
                echo $_POST['token'];
            else
            {
                $xml->addChild("token", $_POST['token']);
                unlink("tokens.xml");
                $xml->saveXML("tokens.xml");
                echo $_POST['token'];
            }
        }
        else
            echo "Error";

    }
  • 写回答

1条回答 默认 最新

  • doucaishou0074 2011-02-21 05:40
    关注

    Weird error. Perhaps a race condition, in which case you should look into flock(). Actually, what you'd have to do is flock() a dummy file that serves as global lock, write the new file under a temporary name then rename the file to "tokens.xml". So basically you're implementing your own concurrency control... which is never a good sign.

    Ideally, you should really use a database instead.

    On a side-node, file_put_contents() is supposed to be atomic IIRC. I don't know if SimpleXMLElement::asXML() is.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度