我有以下格式的一些xml数据 -
<xyz:reqResponse
xmlns:xyz="http://www.test.com/xyz/"
xmlns:akt="http://www.exmple.com/akt/">
<xyz:version>1.2</xyz:version>
<xyz:totalRecords>659</xyz:totalRecords>
<xyz:records>
<xyz:record>
<doc>
<str name="icon_url">http://www.icons.net/icon1.jpg</str>
<str name="type">Service</str>
<arr name="bc.recordTitle"><str>Evergreen Club</str></arr>
<str name="bc.id">KLM0078</str>
<str name="system.external.id">787678</str>
<arr name="bc.description">
<str>Meetings: Church Hall Beaudesert Lane. Open to anyone over 50.</str>
</arr>
<str name="code">X1209</str>
<double name="localval1">-4.00006</double>
<double name="localval2">-7.00012</double>
<date name="timestamp">Wed Jun 02 21:19:33 BST 2010</date>
</doc>
</xyz:record>
<xyz:record>
<doc>
<str name="icon_url">http://www.icons.net/icon1.jpg</str>
<str name="type">Service</str>
<arr name="bc.recordTitle"><str>Evergreen Club</str></arr>
<str name="bc.id">KLM0078</str>
<str name="system.external.id">787678</str>
<arr name="bc.description">
<str>Meetings: Church Hall Beaudesert Lane. Open to anyone over 50.</str>
</arr>
<str name="code">X1209</str>
<double name="localval1">-4.00006</double>
<double name="localval2">-7.00012</double>
<date name="timestamp">Wed Jun 02 21:19:33 BST 2010</date>
</doc>
</xyz:record>
</xyz:records>
</xyz:reqResponse>
我喜欢
$xml = simplexml_load_string($xml_data);
$namespaces = $xml->getNameSpaces(true);
$data = $xml->children($namespaces['xyz']);
所以,如果我打印
echo $data->totalRecords; //outputs correctly 659
我正在尝试遍历所有记录并访问各个字段,但不知道如何做到这一点。
我试过像
这样的东西$records = $data->records;
foreach($records as $record) {
echo print_r($record, true);
}
但它没有帮助。
我的问题是 -
- 如何访问每个<xyz:record>
及其子项(<str name="abc">NAbc</str>
等?
谢谢, 凯
答案 0 :(得分:2)
我会使用xpath()方法:
$xml = simplexml_load_string($xml_data);
$xml->registerXPathNamespace('xyz', 'http://www.test.com/xyz/');
$recordArr = $xml->xpath('/xyz:reqResponse/xyz:records/xyz:record');
foreach($recordArr as $record) {
$strArr = $record->xpath('doc/str');
foreach($strArr as $str) {
do what you want with $str
}
}
(未测试)。
答案 1 :(得分:1)
当您选择$data->records
时,您选择了所有records
个元素,而不是record
,我认为您应该使用$data->records->record
来识别所有record
元素。< / p>
$records = $data->records->record;
foreach($records as $record){
$doc = $record->doc;
//Now here you can access all str elements itering through $doc->str elements.
}
这是PHP示例:SimpleXMLElement
更新(正如我们在意大利所说的“你永远不会停止学习”)
只有当xml元素共享相同的命名空间时,才可以将它们作为对象访问,您可以这样做:
$docsCollection = $record->children(); //This will retrieve children within default namespace
$strCollection = $docs->doc->str; //Now we are in the same namespace and can reuse above notation
仅供记录。