《PHP采集今日頭條內(nèi)容頁時(shí),解析頁面上的JS轉(zhuǎn)為json》要點(diǎn):
本文介紹了PHP采集今日頭條內(nèi)容頁時(shí),解析頁面上的JS轉(zhuǎn)為json,希望對您有用。如果有疑問,可以聯(lián)系我們。
在采集今日頭條時(shí),由于是用JS的AJAX來獲取內(nèi)容,因此需要解析JS。
如果你截取到了內(nèi)容頁上的JS,并用PHP的JSON轉(zhuǎn)化為對象。發(fā)現(xiàn)并不容易,因?yàn)樯厦娴暮瘮?shù)格式并不規(guī)范,比如:
這是頁面上的標(biāo)題:
{title : '這是標(biāo)題,用單引號包圍,PHP中JSON不能解析,需要換成雙引號'}
現(xiàn)在想轉(zhuǎn)成PHP的OBJECT,單純用
$js = json_decode ($str);
是不行的。
使用下面函數(shù),可以過濾清理。
function json_decode_convert($str, $mode=false){ $str = str_replace("''", '""', $str); $str = preg_replace('/([a-zA-Z]+)\s*:/is', '"$1":', $str); $str = preg_replace("/\'(.+?)\'/is", '"$1"', $str); $str = preg_replace("/:\s*([^\"\s,\{\}]+)/is", ':"$1"', $str); return json_decode($str, $mode); }
執(zhí)行下試試:
$js = json_decode_convert ($str); print_r ($js);
結(jié)果如圖:
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/5763.html