douju5062 2016-12-07 13:07
浏览 85
已采纳

PHP SimpleXMLElement对象获取数据

I have the following XML:

<Root>
    <personalData>
        <userName>John Tom</userName>
        <email>mail@example.com</email>
    </personalData>
    <profesionalData>
        <job>engineer</job>
        <jobId>16957</jobId>
    </profesionalData>
</Root>

Doing in my debugger:

$myObject->xpath('//Root/profesionalData')

I have:

: array = 
  0: object(SimpleXMLElement) = 
    job: string = engineer    
    jobId: string = 16957

I cannot get hold of the jobId 16957.

What do I have to do?

  • 写回答

1条回答 默认 最新

  • doupu0619 2016-12-07 13:12
    关注
    $root = simplexml_load_file('file.xml');
    
    
    $job_ids = $root->xpath('//profesionalData/jobId');
    
    if (!$job_ids) {
      die("Job IDs not found");
    }
    
    foreach ($job_ids as $id) {
      // SimpleXmlElement implements __toString method, so
      // you can fetch the vlaue by casting the object to string.
      $id = (string)$id;
      var_dump($id);
    }
    

    Sample Output

    string(5) "16957"
    

    Notes

    You don't need to specify Root in the XPath expression, if you are going to fetch all profesionalData/jobId tags no matter where they are in the document, just use the double slash (//) expression. This approach may be convenient in cases, when you want to avoid registering the XML namespaces. Otherwise, you can use a strict expression like /Root/profesionalData/jobId (path from the root). By the way, your current expression (//Root/profesionalData/jobId) matches all occurrences of /Root/profesionalData/jobId in the document, e.g. /x/y/z/Root/profesionalData/jobId.

    Since SimpleXmlElement::xpath function returns an array on success, or FALSE on failure, you should iterate the value with a loop, if it is a non-empty array.

    SimpleXmlElement implements __toString method. The method is called when the object appears in a string context. In particular, you can cast the object to string in order to fetch string content of the node.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 就很莫名其妙,本来正常的Excel,突然变成了这种一格一页
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?