3

How i can check in php if the url contains xml of json file. so in the $url holds the url and than it should check whethere it is a xml file or a json file.

$url = 'http://hello.asdasd/asdasd/asdasd';

if (($url == JSON) = TRUE){ // how to  check it is a json file, do the follwing action

    $xml = file_get_contents($url);
    $json = json_decode($xml, true);
} 
else if ($url == XML) = TRUE){ // how to check it is a XML file, do the follwing action
    $xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA);
}

Any advice will be really appreciable.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Istiak Mahmood
  • 2,330
  • 8
  • 31
  • 73

2 Answers2

8

Simple process:

You have most of this code already, just adjust your if statements to check the results of attempting to decode/load the data.

Also since it's a web resource, you could cross-check the mime type. This would require using something other than file_get_contents().

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1

I would suggest using the solution for checking a file is valid Json.

Then you simply check if the string is JSON then assume XML - if it's guaranteed to be one or the other!

Community
  • 1
  • 1
udjamaflip
  • 682
  • 1
  • 8
  • 24