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

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.

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

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站