Miguel Mas
Miguel Mas

Reputation: 545

PHP SimpleXMLElement object get data

I have the following XML:

<Root>
    <personalData>
        <userName>John Tom</userName>
        <email>[email protected]</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?

Upvotes: 0

Views: 261

Answers (1)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21502

$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.

Upvotes: 1

Related Questions