user1096935
user1096935

Reputation: 33

Converting XML to JSON with PHP

How would I pull an xml file from an external site to encode in JSON? I want to be able to check if a value in the XML file is true or false but I only know how to do that with JSON and cannot find anything on how to do this with XML. This is what I am doing with JSON using a JSON API pull:

$stringData = "<a href=\"http://www.twitch.tv/coldrewbie\"</a>coL.drewbie<br>\n";
$json_file = file_get_contents("http://api.justin.tv/api/stream/list.json?channel=coldrewbie");
$json_array = json_decode($json_file, true);

if ($json_array[0]['name'] == 'live_user_coldrewbie') {
    fwrite($fh, $stringData);
}

The only problem is that the other site I want to pull from uses an XML document for its API vs having the JSON option. This is what I have but I do not think it is right although I might be somewhat close:

$xml = simplexml_load_file("http://api.own3d.tv/liveCheck.php?live_id=173952");
$json_file = json_encode($xml);
$json_array = json_decode($json, true);

if ($json_array[0]['isLive'] == 'true'){
    echo "yup";
}

Any help would be awesome!

Upvotes: 3

Views: 871

Answers (1)

Abbas
Abbas

Reputation: 6886

You are on the right track. Once you have loaded the XML with this:

$xml = simplexml_load_file("http://api.own3d.tv/liveCheck.php?live_id=173952");

You can get the value of isLive node by calling the xpath method and passing it an xpath query:

$result = $xml->xpath("/own3dReply/liveEvent/isLive");

This methods returns an array, so you can either iterate the result or just print it out:

print($result[0]);

Don't forget to check both $xml and $result before going any further with them. I have had bad experiences relying on data pulled from external websites.

Upvotes: 1

Related Questions