SimpleXML and namespaces

2019-01-15 19:54发布

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.

3条回答
Animai°情兽
2楼-- · 2019-01-15 20:35

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";
}
查看更多
我命由我不由天
3楼-- · 2019-01-15 20:40

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

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-15 20:52

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;
    }
}
查看更多
登录 后发表回答