简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM