You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SimpleHtmlDom提取JSON中第二个@type为user的name和url

解决方案
  1. 解析JSON文本为PHP数组
    先将获取到的JSON内容转换为可操作的PHP数组,注意原JSON结构外层缺少大括号,需先补全(否则json_decode会解析失败)。

  2. 筛选并定位目标数据
    从数组中取出offers->offers列表,筛选出所有@type为user的项,再取第二个元素(PHP数组索引从0开始,对应索引1)。

  3. 输出目标字段
    提取该元素的name和url并按要求格式输出。

完整代码示例

// 获取JSON脚本内容
$jsonElement = $html->find('script[type="application/ld+json"]', 0);
$jsonText = $jsonElement->innertext;

// 补全JSON外层大括号(原结构缺失)
$jsonText = '{' . trim($jsonText) . '}';

// 解析为PHP关联数组
$data = json_decode($jsonText, true);

// 筛选所有@type为user的项
$userItems = array_filter($data['offers']['offers'], function($item) {
    return isset($item['@type']) && $item['@type'] === 'user';
});

// 重新索引数组,确保能通过索引定位
$userItems = array_values($userItems);

// 输出第二个符合条件的用户信息
if (isset($userItems[1])) {
    $targetUser = $userItems[1];
    echo '"name": "' . $targetUser['name'] . '",' . PHP_EOL;
    echo '"url": "' . $targetUser['url'] . '"';
} else {
    echo '未找到第二个@type为user的项';
}

说明

  • 补全外层大括号是因为原JSON结构缺少最外层包裹,否则无法正常解析。
  • 使用array_filter能确保只保留符合类型要求的项,避免列表中混杂其他类型数据影响定位。
  • 用array_values重新索引数组,保证即使原列表有非user类型项,也能准确获取第二个user项。

内容的提问来源于stack exchange,提问作者h1h2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 10:33:19