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

如何使用PHP cURL解析XML接口数据并提取last_name字段值

问题定位

你代码的问题主要有3处:

  1. 接口请求参数错误:你原本要请求的是用户列表接口,但代码里错误对baseUrl做了{user_id}占位符替换,额外加了单个用户查询的参数,导致返回的XML结构和你提供的示例列表结构不一致。
  2. XML遍历层级错误:你用SimpleXMLElement加载返回结果后,根节点本身就是<users>标签,不需要再访问$oXML->users,直接遍历根节点下的user子节点即可。
  3. 取值逻辑错误:你直接echo未定义的常量last_name,没有从遍历得到的user节点中提取对应属性,而且输出SimpleXMLElement对象需要先转成字符串。

修正后可运行代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>提取用户姓氏</title>
</head>
<body>
    <?php
    $ch = curl_init();
    // 直接使用用户列表接口,不需要替换user_id占位符
    $baseUrl = 'https://api-eu.hosted.exlibrisgroup.com/almaws/v1/users';
    $queryParams = array(
        'limit' => 10,
        'offset' => 0,
        'order_by' => 'last_name, first_name, primary_id',
        'apikey' => 'l8xx7b65eb296f6c43d1af7d005aac0dbcf8'
    );
    $url = $baseUrl . "?" . http_build_query($queryParams);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    // 加载XML
    $oXML = new SimpleXMLElement($response);

    // 直接遍历根节点下的user子节点
    foreach ($oXML->user as $user) {
        // 转成字符串输出last_name
        echo (string)$user->last_name . "<br>";
    } 
    ?>
</body>
</html>

运行后会按顺序输出所有last_name的值:AABAIDA、ABADIE、ABADIE、ABAR、ABAR、ABAR、ABDEREMANAR、ABDERRAHIM、ABDERREZAGUE、ABDESSAMED。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:06:01