0

我使用 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'];
}

?>
4

2 回答 2

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

观看现场演示

于 2012-10-16T09:41:55.997 回答
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
于 2012-10-16T09:47:10.780 回答