简体   繁体   English

检索特定xml数据时出现问题

[英]Issue retrieving specific xml data

For the last several hours I've been trying to retrieve specific data from an XML file https://cdn.animenewsnetwork.com/encyclopedia/api.xml?title=1 在过去的几个小时中,我一直在尝试从XML文件https://cdn.animenewsnetwork.com/encyclopedia/api.xml?title=1检索特定数据。

The data which I'm trying to retrieve is located with type "Genres", Ideally I've been trying to place "Genres" into a loop because of the different XML files having a different number of "Genres". 我要检索的数据的类型为“流派”,理想情况下,由于不同的XML文件具有不同的“流派”数量,我一直试图将“流派”放入循环中。

I've been reading the XML and PHP manual as well as Googling to find a possible solution but I've drawn a blank, if anyone is able to point me in the right direction I'd greatly appreciate it, thank you. 我一直在阅读XML和PHP手册以及Google搜索来找到可能的解决方案,但是我已经空白了,如果有人能够指出正确的方向,我将非常感谢,谢谢。

I've tried to use an if statement but the expected results was not what was displayed 我尝试使用if语句,但是预期结果不是所显示的结果

$url = "https://cdn.animenewsnetwork.com/encyclopedia/api.xml?title=1";

$result = simplexml_load_file($url);

foreach ($result->anime as $data) {

foreach ($result->anime as $data) {
    if ($a['type'] = "Genres") {
        foreach ($data->info as $info) {
            $a = $info->attributes();
            echo $a['type']." : ".$a['src'] .$info. "<br>";
        }
    }
}

I expect to output to be anything between the > and < brackets that has the type="Genres", the expected output should say "action drama science fiction" but the actual output is all the data from "Picture" to "Official website" from the XML file. 我希望输出的是在>和<之间的任何类型,类型为“类型”,预期的输出应为“动作戏剧科幻小说”,但实际输出是从“图片”到“官方网站”的所有数据从XML文件。

You have a few bugs in your code, but you can also achieve what you want without having to test for each attribute yourself. 您的代码中有一些错误,但是您也可以实现所需的功能,而不必亲自测试每个属性。 Using XPath allows you to retrieve a list of the elements you want. 使用XPath可以检索所需元素的列表。

This code uses //info[@type='Genres'] which means any <info> node which has an attribute type equal to Genres . 这段代码使用//info[@type='Genres'] ,这意味着属性type等于Genres任何<info>节点。 The call to xpath() will return a list of just the matching elements, so no need to test anything more, just output the information your after... xpath()的调用将返回仅包含匹配元素的列表,因此无需进行任何其他测试,只需在之后输出信息即可。

$url = "https://cdn.animenewsnetwork.com/encyclopedia/api.xml?title=1";

$result = simplexml_load_file($url);

foreach ($result->xpath("//info[@type='Genres']") as $data) {
    echo $data['type']." : " .(string)$data. "<br>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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