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 学不会递归,理解不了汉诺塔参数变化
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)