Reputation: 307
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
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".
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.
I've tried to use an if statement but the expected results was not what was displayed
$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.
Upvotes: 0
Views: 26
Reputation: 57131
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.
This code uses //info[@type='Genres']
which means any <info>
node which has an attribute type
equal to Genres
. 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...
$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>";
}
Upvotes: 1