[英]Converting XML to JSON with PHP
How would I pull an xml file from an external site to encode in JSON? 如何从外部站点提取xml文件以使用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. 我希望能够检查XML文件中的值是真还是假,但我只知道如何使用JSON执行此操作,并且无法找到有关如何使用XML执行此操作的任何内容。 This is what I am doing with JSON using a JSON API pull: 这就是我使用JSON API拉取JSON的方法:
$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. 唯一的问题是我想要提取的其他网站使用XML文档作为其API而不是使用JSON选项。 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后:
$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: 您可以通过调用xpath方法并向其传递xpath查询来获取isLive
节点的值:
$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. 在继续使用它们之前,不要忘记检查$xml
和$result
。 I have had bad experiences relying on data pulled from external websites. 我依赖从外部网站获取的数据有过糟糕的经历。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.