0

我已经抓取了一些javascript(使用simple_html_dom),这就是我想出的......

$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>

我正在尝试获取initialInfoPHP 变量的内容,以便可以执行此操作....

$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
}

任何人都知道我该怎么做(最好简单)?

4

4 回答 4

1

要将其视为 JSON,您必须修复一些问题:

  • JSON 使用双引号,而不是单引号。
  • 中的两个连续逗号..., '1 : 1', '2 : 3', , , '2 : 3'],不是有效的 JSON。
  • 您必须修剪变量声明 ( var initialInfo =)。
  • 你必须剪掉那个结尾的分号。

您也可以编写自己的解析器,因为此代码仅使用数组文字、字符串和数字。

于 2013-07-18T23:55:24.273 回答
0

这可能会给你字符串:

function js_array($str, $array_name)
{
    $pattern = "/$array_name ?\[[\s\S]*?\] ?\= ?[\'\"]([\s\S.]*?)[\'\"];/";

    preg_match_all($pattern, $str, $matches);

    $array = (isset($matches[1])) ? $matches[1] : array();

    return $str;
}
$str = js_array($MyScrape, 'initialInfo');

然后我可能会尝试 json_decode,正如你提到的。

让我知道它是否有效(或无效)!

于 2013-07-18T23:54:00.800 回答
0

它可能不适用于旧浏览器,但您可以使用JSON.stringify(initialinfo),并将其存储到隐藏字段中,然后使用 PHP 将其提取。

于 2013-07-19T00:01:50.180 回答
0

好的,这就是我为使其正常工作所做的工作....

//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
于 2013-07-19T01:38:01.707 回答