SimpleXML and namespaces

I have following code.


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:

    $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', '');
$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 or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply