panduanvip/ronolo-json-extract

从字符串中提取JSON并返回PHP数组。

安装: 68

依赖: 2

建议者: 0

安全性: 0

星标: 0

关注者: 0

分支: 2

语言:HTML

1.2.1 2021-05-16 15:48 UTC

This package is auto-updated.

Last update: 2024-09-18 00:56:10 UTC


README

摘要

一个小的类,尝试从一个字符串中提取JSON字符串。有两个函数可以做到这一点。

This fork fixes the problem on "Array and string offset access syntax with curly braces that no longer supported"

安装

composer require panduanvip/ronolo-json-extract

使用

<?php
use RoNoLo\JsonExtractor\JsonExtractorService; 
 
$jsonExtractor = new JsonExtractorService();
 
// $html contains a HTML full page string (as example)
$html = file_get_content('foo/bar.html');
$json = $jsonExtractor->extractJsonAfterIdentifier("foobar", $html);

这将期望标识符出现在给定的字符串中。标识符的位置将作为起点,并返回下一个有效的JSON对象或数组作为PHP数组。

<?php
use RoNoLo\JsonExtractor\JsonExtractorService; 
 
$jsonExtractor = new JsonExtractorService();
 
// $html contains a HTML full page string
$html = file_get_content('foo/bar.html');
$vars = $jsonExtractor->extractAllJsonData($html);

这将寻找字符串中的任何JSON对象或数组,并将它们作为JSON数据的数组数组返回。您可能需要检查JSON数据列表以找到所需的数据。

建议使用DOM解析器(如symfony/dom-crawler)将HTML分解成更小的部分。要解析的部分越小,结果越好。

例如,如果您解析一个HTML字符串并期望JSON在...

...标签内,只需将标签内的文本传递给json-extract函数。

可以提取

正确的JSON

{
  "paging": {
    "pageNum": 1,
    "pageSize": 25,
    "numFound": 1,
    "last": 1,
    "lastUncapped": 1,
    "display": [1]
  }
}

不正确的单引号JSON

{
  'paging': {
    'pageNum': 1,
    'pageSize': 25,
    'numFound': 1,
    'last': 1,
    'lastUncapped': 1,
    'display': [1]
  }
}

JavaScript对象(感谢CJSON.php)

{
  paging: {
    pageNum: 1,
    pageSize: 25,
    numFound: 1,
    last: 1,
    lastUncapped: 1,
    display: [1]
  }
}

EOF