使用php解析javascript文件

时间:2011-03-23 02:43:33

标签: php javascript parsing

我尝试使用以下内容并且它没有返回所有JavaScript。

$homepage = file_get_contents('dr_0702/.js');

echo $homepage;

我正在尝试返回JavaScript源代码,以便我可以解析其中的一些内容。这就是我要解析的内容:

但是从这段代码我只想解析msgTitle,msgBody,insertDate

1 个答案:

答案 0 :(得分:0)

我把这个功能放在一起就是为了这个目的。我的函数查找一个唯一的起始字符串,在这种情况下类似msgTitle“:”,然后它抓住每个字符,直到它遇到结束字符串,在这种情况下是双引号。

要使用它,您将执行以下PHP语句:

$msgTitle = parse_to_string('msgTitle":"', '"', $homepage);

$msgBody = parse_to_string('msgBody":"', '"', $homepage);

$insertDate = parse_to_string('insertDate":"', '"', $homepage);

这是PHP函数

function parse_to_string($beginning_string, $ending_string, $custom_string='')
{

    // . in Regular Expressions means match any character
    // * in Regular Expressions means "greedy" and grab everything up to the ending string
    // siU in Regular Expressions means ignore case sensitivity

    if('' != $custom_string){

        // Search $html variable for all characters between the begin and end strings 
        // INCLUDING the begin and end strings  
        preg_match_all("($beginning_string.*$ending_string)siU", $custom_string, $matching_data);


            return $matching_data[0][0];

    }
            else { return false; }

}