我使用Simplexml和xpath来解析我的XML。
这是我的xml输出:
<?xml version="1.0"?>
<api>
<query>
<categorymembers>
<cm pageid="30908" ns="0" title="Thomas Acda" />
<cm pageid="46896" ns="0" title="Elvan Akyildiz" />
<cm pageid="21162" ns="0" title="Jenny Arean" />
<cm pageid="30913" ns="0" title="Tijl Beckand" />
<cm pageid="829" ns="0" title="Yoka Berretty" />
<cm pageid="45" ns="0" title="Wim de Bie" />
<cm pageid="31894" ns="0" title="Jan Blaaser" />
<cm pageid="832" ns="0" title="Karin Bloemen" />
<cm pageid="833" ns="0" title="Hetty Blok" />
<cm pageid="12473" ns="0" title="Ron Boszhard" />
<cm pageid="34605" ns="0" title="Ansje van Brandenberg" />
<cm pageid="8451" ns="0" title="Claudia de Breij" />
<cm pageid="678" ns="0" title="Jos Brink" />
<cm pageid="29595" ns="0" title="Joke Bruys" />
<cm pageid="30909" ns="0" title="Horace Cohen" />
<cm pageid="689" ns="0" title="Gerard Cox" />
<cm pageid="32008" ns="0" title="Pieke Dassen" />
<cm pageid="31047" ns="0" title="Wieteke van Dort" />
</categorymembers>
</query>
</api>
这是我的代码来显示标题。
<?php
$xml = new SimpleXMLElement('http://www.beeldengeluidwiki.nl/api.php?action=query&list=categorymembers&cmtitle=Category:Cabaretier&cmlimit=400', null, true);
$data = $xml->xpath("/api/query/categorymembers/cm");
foreach ($data as $item) {
echo $item['title'];
}
?>
答案 0 :(得分:1)
它们是属性
$xml = new SimpleXMLElement($xml);
echo "<pre>";
foreach($xml->query->categorymembers->children() as $cm)
{
list($pageid, $ns, $title) = $cm->attributes();
echo $pageid , " " , $ns , " " , $title , PHP_EOL ;
}
输出
30908 0 Thomas Acda
46896 0 Elvan Akyildiz
21162 0 Jenny Arean
30913 0 Tijl Beckand
829 0 Yoka Berretty
45 0 Wim de Bie
31894 0 Jan Blaaser
832 0 Karin Bloemen
833 0 Hetty Blok
12473 0 Ron Boszhard
34605 0 Ansje van Brandenberg
8451 0 Claudia de Breij
678 0 Jos Brink
29595 0 Joke Bruys
30909 0 Horace Cohen
689 0 Gerard Cox
32008 0 Pieke Dassen
31047 0 Wieteke van Dort
答案 1 :(得分:0)
你可以像这样使用DOM解析器:
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($xml);
$xpath = new DOMXPath($doc);
$nlist = $xpath->query("//api/query/categorymembers/cm");
$numnodes = $nlist->length;
for($i=0; $i < $numnodes; $i++) {
$node = $nlist->item($i);
echo ($i+1) . ':'. $node->getAttribute('title') . "\n";
}
<强>输出:强>
1:Thomas Acda
2:Elvan Akyildiz
3:Jenny Arean
4:Tijl Beckand
5:Yoka Berretty
6:Wim de Bie
7:Jan Blaaser
8:Karin Bloemen
9:Hetty Blok
10:Ron Boszhard
11:Ansje van Brandenberg
12:Claudia de Breij
13:Jos Brink
14:Joke Bruys
15:Horace Cohen
16:Gerard Cox
17:Pieke Dassen
18:Wieteke van Dort