drzyeetvt41077335 2011-11-14 20:58
浏览 244
已采纳

Php Javascript将document.write的内容写入变量

I'm in front of this problem that I can't figure out how to solve properly.

I'm using a script:

<script type="text/javascript" src="http://www.gta4.it/stat/view_stats.js.php?mode=0">  </script>

that has as output a single document.write:

document.write('11');

And so the number is displayed using JavaScript. What I want to do is to get the content of this document.write and write it into a variable, JavaScript or PHP, in another server.

Any idea?

  • 写回答

4条回答 默认 最新

  • douqiandai4327 2011-11-14 21:07
    关注

    That script is just outputting a small JavaScript snippet - You don't need to actually let it execute in the browser if you want to capture its result in PHP:

    // Assuming you have [allow_url_fopen][1] enabled
    $js = file_get_contents( 'http://www.gta4.it/stat/view_stats.js.php?mode=0');
    $value = trim( str_replace( array( "document.write('", "');"), '', $js));
    echo $value; // Outputs 9, the current value of the JS
    

    Demo

    Of course, if you're looking for a more robust solution that would still work if the JS snippet changes (introduces whitespace, changes quotation types, etc), you can use a regex to extract the number from the snippet. Something like this should work:

    $js = file_get_contents( 'http://www.gta4.it/stat/view_stats.js.php?mode=0');
    $value = preg_replace('/^\s*document\.write\(\s*[\'"](\d*)[\'"]\s*\)\s*;\s*$/im', '$1', $js);
    echo $value; // Outputs 11, the now current value of the JS
    

    Demo

    If, for some reason, you want / need to let it execute in a browser before capturing the value, you can do something like this, although I'm sure it's not standards-compliant and seems pretty hackish.

    1. Wrap the <script> tag in a container, perhaps a <span> or <div>
    2. Use JS to get the contents of the container.
    3. Use AJAX to send the result to a server.

    Sample (untested):

    <div id="stats_container">
        <script type="text/javascript" src="http://www.gta4.it/stat/view_stats.js.php?mode=0">  </script>
    </div>
    <script type="text/javascript"> 
        var value = document.getElementById( 'stats_container').innerHTML;
        alert( value); // Here you would use AJAX to send the value to a server
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?