SimpleXML and namespaces

I have following code.

 <entry>
  <job:location>
   <job:id>24</job:id>
   <job:region>6</job:region>
  </job:location>
 </entry>

I’ve problem with namespaces. How I can read content of job:region tag in SimpleXML.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Try this:

 <?php 
    $entry = simplexml_load_file('entry.xml');        
    printf("%s\n", $entry->children('job', true)->location->region);  
 ?> 

To check the above code in action, click here

For more information about SimpleXml refer to this article

Solution 2

You should register the job namespace, then you can use the registered namespace-prefix in an XPath to select what you want:

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('job', 'http://example.org/you-did-not-provide-the-job-namespaceURI-in-your-example');
$result = $sxe->xpath('//entry/job:location/job:region');

foreach ($result as $location) {
  echo $location . "\n";
}

Solution 3

I would do it dynamically.

$xml = @simplexml_load_string($path) // loads your valid xml data
foreach($xml->channel->item as $entry) {

  $namespaces = $entry->getNameSpaces(true);
  foreach($namespaces as $ns=>$value)
  {
    $job = $entry->children($namespaces[$ns]);
    $author = (string)$job->creator;

    if ($author != "")
    {
      $someVariable = (string) $dc->creator;
    }
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply