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条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题