ronolo/json-extract

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

1.2.0 2020-10-01 18:47 UTC

This package is auto-updated.

Last update: 2024-09-04 20:37:23 UTC


README

摘要

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

安装

composer require ronolo/json-extract

如果不起作用,您可能需要将仓库添加到顶级composer.json的顶部,如下所示

{
  "repositories": [
     {
        "type": "vcs",
        "url":  "https://github.com/ronolo/json-extract.git"
    }
  ]
}

使用

<?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