Using php to check if xml is atom or rss

I am writing PHP code that should determine if a given xml is in the format of "atom" or "rss". After observing atom and rss xml files, I decided to classify xml based on the root element. If the root element "<feed"is an xml atom. If it is "<rss"not an atom.

How can I do this check with the DOM? So far I have:

$dom = new DOMDocument();
$dom->loadXML($resp);
$feed = $dom->getElementsByTagName("feed");
if($feed != NULL)
echo 'it\ a atom!';

but it doesn’t work absolutely right .... There are no errors, he just writes "this is an atom", even if it is not

+3
source share
5 answers

I agree that you can get this hint easier. If you are looking for the name of the root element, check:

$dom->documentElement->tagName;

, , .

+3

, $resp - , .

$xml = simplexml_load_file($filepath);
$root_element_name = $xml->getName();
if ($root_element_name  == 'feed') {
    // is atom feed

} else if ($root_element_name  == 'rss') {
    // is rss feed

}

XML node. node , , node rss, rss.

+7

$dom DOMDocument - :

$dom->loadXML($resp);
if($dom->getElementsByTagName("feed")->length > 0 && $dom->getElementsByTagName("rss")->length <= 0){
  // atom feed
}else{
  // rss feed
}

( DOMDocument, - , )

EDIT:

- wahts wron null. getElementsByTagName DOMNodeList (, )

+2

null :

$dom = new DOMDocument();
$dom->loadXML($resp);
$feed = $dom->getElementsByTagName("feed");
if($feed->length != 0) {
    echo 'it\ a atom!';
}
0

, / , application/atom+xml. , strpos('http://www.w3.org/2005/Atom').

0

Source: https://habr.com/ru/post/1783250/


All Articles