簡體   English   中英

使用PHP和cURL從混合文本/ html / javascript文件中提取JSON數據

[英]Use PHP and cURL to pull JSON data from mixed text / html / javascript file

鏈接上使用PHP和cURL,返回包含類似於以下信息的文件:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <script>
            window['flyerData'] = {
                "id":489640,
                "categories":[{
                    "id":527,
                    "flyer_category_id":1201344,
                    "run_category_id":null,
                    "skipped":null,
                    "name":"Pharmacy",
                    "left":2925.0,
                    "bottom":-2560.0,
                    "right":4388.0,
                    "top":0.0,
                    "thumbnail_image_url":null
                }]
            }
        </script>
    </body>
</html>

如您所見,結果混合了html / javascript。 我想做的是使用window['flyerData']因此我可以根據需要過濾值。

如何使用PHP和cURL做到這一點?

您可以執行以下操作(未經測試):

<?php
    //get the contents of the curl call
    $curlOutput = "<!DOCTYPE html>
                        <html>
                            <head></head>
                            <body>
                                <script>
                                    window['flyerData'] = {
                                        "id":489640,
                                        "categories":[{
                                            "id":527,
                                            "flyer_category_id":1201344,
                                            "run_category_id":null,
                                            "skipped":null,
                                            "name":"Pharmacy",
                                            "left":2925.0,
                                            "bottom":-2560.0,
                                            "right":4388.0,
                                            "top":0.0,
                                            "thumbnail_image_url":null
                                        }]
                                    }
                                </script>
                            </body>
                        </html>";
    //strip out everything except for the values between the first '{' and the last '}'
    $json = substr($curlOutput, stripos($curlOutput, '{'), strripos($curlOutput, '}'));
    //parse that string as JSON
    $decodedJson = json_decode($json);
    var_dump(decodedJson);
    var_dump(decodedJson.categories);
?>

但是請注意,這種類型的解析被認為是脆弱的,因為不能保證curl調用中的字符串格式繼續符合當今的HTML / JS。 這就是為什么如果可以訪問的話,定義良好的API是更好的選擇的原因。

這非常適合拉出我想要的字符串:

preg_match('/window\[\'flyerData\'\] \= (\{.*\};)/', $responseBody, $matches);
echo $matches[1];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM