0
<url>
    <loc>http://example.com</loc>
    <news:news>
        <news:publication_date>2015-05-11</news:publication_date>
        <news:title>Some news content</news:title>
        <news:keywords/>
    </news:news>
</url>

<url>
    <loc>http://example2.com</loc>
    <news:news>
        <news:publication_date>2015-05-12</news:publication_date>
        <news:title>Some news content 2</news:title>
        <news:keywords/>
    </news:news>
</url>

How can get news:publication_date, news:title, news:keywords

I can get <loc>'s value but <news: tag getting null

$xml=simplexml_load_file("http://example.com") or die("Error!");

foreach($xml->url as $key){
    $URL = $key->loc;
    //What should I do here to get title, keywords, publication_date
}
hakki
  • 6,181
  • 6
  • 62
  • 106
  • for corrext xml file in first line a line must be such as which define namespace. – splash58 May 11 '15 at 14:00
  • I have it. For clear understanding I removed them. – hakki May 11 '15 at 14:02
  • in the case really read link by ihsan – splash58 May 11 '15 at 14:04
  • Removing the xmlns attributes breaks and changes the document. Don't do that. Please post valid XML, so it is possible to reproduce your problem. – ThW May 11 '15 at 18:19
  • It's important you post as well the xml namespace prefix declarations of that document otherwise this can't be answered. I suppose XML namespaces is a new concept to you and I close against a duplicate that shows how to read "element names with colons". – hakre May 11 '15 at 21:20

2 Answers2

0

The simplest way is to suppressing error and ask without news:

$a = '<url>
    <loc>http://example.com</loc>
    <news:news>
        <news:publication_date>2015-05-11</news:publication_date>
        <news:title>Some news content</news:title>
        <news:keywords/>
    </news:news>
</url>';

$xml = @simplexml_load_string($a);

echo $xml->news->publication_date;

result:

2015-05-11
splash58
  • 26,043
  • 3
  • 22
  • 34
-1

I solved this problem. If xml has namespaces you should use getNamespaces(). Clear understanding compare my question and below answer.

$xml = simplexml_load_file("http://example.com") or die("Error!");

$ns = $xml->getNamespaces(true); // I ADDED THIS

foreach($xml->url as $key){

    $news  = $key->children($ns["news"]); //THIS

    $URL   = $key->loc;
    $PUBLISH_DATE = $news->news->publication_date; //THIS
    $TITLE = $news->news->title;  //AND THIS
}

If you want to read about getNamespaces(): http://www.nusphere.com/kb/phpmanual/function.simplexml-element-getnamespaces.htm

hakki
  • 6,181
  • 6
  • 62
  • 106
  • It doesn't work with your example :( – splash58 May 11 '15 at 16:01
  • 1
    Do not read the namespaces from the document. Fetch the data using the namespaces. Do not depend on the prefixes. They are only aliases and can change and are optional (on elements). – ThW May 11 '15 at 18:13