3

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!

1
  • Can I just bypass the whole json thing and check if an element contains certain content and verify if it is true or false? Then create an if statement that echos what I want it to say? Commented Jan 4, 2012 at 17:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This worked perfectly. Below is the code that worked: //Bomber $stringData = "<a href=\"http://www.own3d.tv/live/173952/StartaleBomber\">StartaleBomber</a><br>"; $xml = simplexml_load_file("http://api.own3d.tv/liveCheck.php?live_id=173952"); $result = $xml->xpath("/own3dReply/liveEvent/isLive"); if ($result[0] == 'true'){ fwrite($fh, $stringData); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.