简体   繁体   English

使用simplexml和xpath解析xml

[英]Parse xml using simplexml and xpath

I use Simplexml and xpath to parse my XML. 我使用Simplexml和xpath来解析我的XML。

This is my xml output: 这是我的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>

and this my code to display the title. 这是我显示标题的代码。

<?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'];
}

?>

They are attributes 它们是属性

$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 ;
}

Output 输出量

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

See Live Demo 观看现场演示

You can use DOM parser like this: 您可以像这样使用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";
}

OUTPUT: 输出:

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

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

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