dongshuo9350 2013-07-18 23:48
浏览 17
已采纳

将javascript变量的内容刮到PHP变量?

I have scraped some javascript (using simple_html_dom) and this is what I've come up with...

Contents of $MyScrape

<script type="text/javascript">
var initialInfo = [
    [
        [29, 30, 'bb1', 'bb2', '02/15/2013 20:00:00', '02/15/2013 00:00:00', 6, 'AT', '1 : 1', '2 : 3', , , '2 : 3'],
        [
            [29, 'bb1', 6.91, [
                    [
                        ['pears', [4]],
                        ['kiwis', [20]]
                    ]
                ],
                [
                    [36849, 'abcdefg', 6.24, [
                        [
                            ['apples', [3]],
                            ['oranges', [0]]
                        ]
                    ], 5, 'iff', 29, 2, 88, 'abc', 23, 180, 76]
                ],
                ['4231', [
                    [5, 1],
                    [7, 7]
                ]]
            ]
        ]
    ], 0
];
</script>

I am trying to get the contents of initialInfo to a PHP variable so I can do this....

$str = ????;
$jsonarray = json_decode($str, true);

foreach($jsonarray as $row)
{
    $id = $row[0][0]; //29
    $tc = $row[0][1]; //30
    $ab = $row[0][2]; //bb1
}

Anyone got an idea how I can do this (preferrably simply)?

  • 写回答

4条回答 默认 最新

  • dongtang9855 2013-07-19 01:38
    关注

    Ok, here's what I did to get this working....

    //Cut out the non-json stuff
      $start = strpos($MyScrape,'initialInfo = ')+14;
      $end = strpos($MyScrape,'</script>');
      $data = substr($MatchDetails, $start, ($end-$start));
    
    //Convert the new string to JSON (as it's not quite right)
    
    //Made single quotes into double so that JSON can read it.
      $fixedJSON = str_replace("'", '"', $data);
    //change double commas with blank data inside so JSON can read it.
      $fixedCommas = str_replace(",,,", ", 0, 0,", $fixedJSON);
    //remove the ending semicolon as JSON can't read it.
      $removedSemiColon = str_replace(";", "", $fixedCommas);
    
    $jsonarray = json_decode($removedSemiColon);
    
    //Now I can actually get stuff out of it...
      echo $row[0][0]; //29
      echo $row[0][1]; //30
      echo $row[0][2]; //bb1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”