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.

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

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化