使用PHP和simplexml从XML检索CDATA内容
时间:2020-03-06 14:35:20 来源:igfitidea点击:
我具有以下XML结构:
<?xml version="1.0" ?>
<course xml:lang="nl">
<body>
<item id="787900813228567" view="12000" title="0x|Beschrijving" engtitle="0x|Description"><![CDATA[Dit college leert studenten hoe ze een onderzoek kunn$
<item id="5453116633894965" view="12000" title="0x|Onderwijsvorm" engtitle="0x|Method of instruction"><![CDATA[instructiecollege]]></item>
<item id="7433550075448316" view="12000" title="0x|Toetsing" engtitle="0x|Examination"><![CDATA[Opdrachten/werkstuk]]></item>
<item id="015071401858970545" view="12000" title="0x|Literatuur" engtitle="0x|Required reading"><![CDATA[Wayne C. Booth, Gregory G. Colomb, Joseph M. Wi$
<item id="5960589172957031" view="12000" title="0x|Uitbreiding" engtitle="0x|Expansion"><![CDATA[]]></item>
<item id="3610066867901779" view="12000" title="0x|Aansluiting" engtitle="0x|Place in study program"><![CDATA[]]></item>
<item id="19232369892482925" view="12000" title="0x|Toegangseisen" engtitle="0x|Course requirements"><![CDATA[]]></item>
<item id="3332396346891524" view="12000" title="0x|Doelgroep" engtitle="0x|Target audience"><![CDATA[]]></item>
<item id="6606851872934866" view="12000" title="0x|Aanmelden bij" engtitle="0x|Enrollment at"><![CDATA[]]></item>
<item id="1478643580820973" view="12000" title="0x|Informatie bij" engtitle="0x|Information at"><![CDATA[Docent]]></item>
<item id="9710608434763993" view="12000" title="0x|Rooster" engtitle="0x|Schedule"><![CDATA[1e semester, maandag 15.00-17.00, zaal 1175/030]]></item>
</body>
</course>
我想从项目标签之一获取数据。要获得此标签,我使用以下xpath:
$description = $xml->xpath("//item[@title='0x|Beschrijving']");
实际上,这确实返回了以下形式的数组:
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 787900813228567
[view] => 12000
[title] => 0x|Beschrijving
[engtitle] => 0x|Description
)
)
)
但是(存储在项目标签之间的)实际信息在哪里?我必须做错了什么,但我无法弄清楚那可能是什么……可能很简单……帮助将不胜感激。
解决方案
我相信它等同于对象上的__toString()方法,因此
echo $description[0];
应该显示它,也可以投射它;
$str = (string) $description[0];
$description = $xml->xpath("//item[@title='0x|Beschrijving']");
while(list( , $node) = each($description)) {
echo($node);
}
dreamwerx的解决方案更好
加载XML文件时,需要处理CDATA。此示例有效:
<?php
$xml = simplexml_load_file('file.xml', NULL, LIBXML_NOCDATA);
$description = $xml->xpath("//item[@title='0x|Beschrijving']");
var_dump($description);
?>
这是输出:
array(1) {
[0]=>
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(4) {
["id"]=>
string(15) "787900813228567"
["view"]=>
string(5) "12000"
["title"]=>
string(15) "0x|Beschrijving"
["engtitle"]=>
string(14) "0x|Description"
}
[0]=>
string(41) "Dit college leert studenten hoe ze een on"
}
}
看一下" SimpleXMLElement"的PHP.net文档(http://uk.php.net/manual/en/function.simplexml-element-children.php),它看起来就像将节点转换为字符串"(string )$ value;"绝招。
失败的话,该页面上有很多示例可以为我们指明正确的方向!

