I get one page html source via phpQuery, and then get below string code from script tag in head via php regex:
var BASE_DATA = {
userInfo: {
id: 0,
userName: 'no-needed',
avatarUrl: 'no-needed',
isPgc: false,
isOwner: false
},
headerInfo: {
id: 0,
isPgc: false,
userName: 'no-needed',
avatarUrl: 'no-needed',
isHomePage: false,
crumbTag: 'no-needed',
hasBar: true
},
articleInfo:
{
title: 'needed',
content: 'needed',
groupId: 'needed',
itemId: 'needed',
type: 1,
subInfo: {
isOriginal: false,
source: 'needed',
time: 'needed'
},
tagInfo: {
tags: [{"name":"no-needed 1"},{"name":"no-needed 2"},{"name":"no-needed 3"}],
groupId: 'no-needed',
itemId: 'no-needed',
repin: 0,
},
has_extern_link: 0,
coverImg: 'no-needed'
},
commentInfo:
{
groupId: 'no-needed',
itemId: 'no-needed',
comments_count: 151,
ban_comment: 0
},};
I want to convert this string to php array, like:
$base_data = array(
'articleInfo' => array(
'title' => 'needed',
'content' => 'needed',
'groupId' => 'needed',
'itemId' => 'needed',
'subInfo' => array(
'source' => 'needed',
'time' => 'needed',
),
));
or
$base_data = array(
'title' => 'needed',
'content' => 'needed',
'groupId' => 'needed',
'itemId' => 'needed',
'subInfo' => array(
'source' => 'needed',
'time' => 'needed',
),);
I already tried with many ways, like: json_decode, get the content from the braces via php regex and the function preg_match_all.But all of them run not well.
I tried two ways:
the first way:
$json = str_ireplace(array('var BASE_DATA =', '};'), array('', '}'), $js);
json_decode($json, true);
the second way:
preg_match_all('/\{([^}]+)\}/', $js, $matches);
print_r($matches[1]);
or
preg_match_all('/articleInfo:\s*\{([^}]+)\}/', $script_text, $matches);
print_r($matches[1][0]);
It seems to close to finish, but it still looks no well, I have to parser string in articleInfo part.... that is why I posted this post.
I even wanted to use V8 JavaScript engine, but.....
do you anyone know the better way to finish it please ?
var BASE_DATA =
part, you're not going to be able to json_decode that until you strip it off. The trailing comma at the end is also an issue, and it may or may not complain about the very last semi-colon. Not sure on that front how forgiving json_decode is.