【发布时间】:2017-01-27 12:24:27
【问题描述】:
在互联网上进行了一些研究后,我意识到 SAX XML Parser 是我的最佳选择,因为我一直在寻找用于大型(非常大)xml 文件的最快 XML Parser。
所以我正在处理我在教程中找到的代码,它确实工作得很好,我只是不知道如何读取第一个和第二个元素的属性,以及每个元素内部的内容。
代码如下:
XML
<?xml version="1.0" encoding="iso-8859-1"?>
<items>
<item id="100" name="First Element 1" />
<item id="101" name="First Element 2" />
<item id="102" name="First Element 3" />
<item id="103" name="First Element 4">
<attribute name="Second Element 4" value="508" />
</item>
<item id="104" name="First Element 5" />
<item id="105" name="First Element 6">
<attribute name="Second Element 6" value="215" />
</item>
</items>
PHP
$items = array();
$elements = null;
$item_attributes = null; //I added that myself, not sure if it's correct
// Called to this function when tags are opened
function startElements($parser, $name, $attrs) {
global $items, $elements, $item_attributes; // <-- added it here aswell
if(!empty($name)) {
if ($name == 'ITEM') {
if (!empty($attrs['ID'])) {
$item_attributes []= array(); // <-- here aswell
}
// creating an array to store information
$items []= array();
}
$elements = $name;
}
}
// Called to this function when tags are closed
function endElements($parser, $name) {
global $elements;
if(!empty($name)) {
$elements = null;
}
}
// Called on the text between the start and end of the tags
function characterData($parser, $data) {
global $items, $elements;
if(!empty($data)) {
if ($elements == 'ATTRIBUTE') {
$items[count($items)-1][$elements] = trim($data);
}
}
}
// Creates a new XML parser and returns a resource handle referencing it to be used by the other XML functions.
$parser = xml_parser_create();
xml_set_element_handler($parser, "startElements", "endElements");
xml_set_character_data_handler($parser, "characterData");
// open xml file
if (!($handle = fopen('./pages/scripts/sax.xml', "r"))) {
die("could not open XML input");
}
while($data = fread($handle, 4096)) {
xml_parse($parser, $data); // start parsing an xml document
}
xml_parser_free($parser); // deletes the parser
$i = 1;
foreach($items as $course) {
echo $i.' -';
echo ' ITEM ID: '.$course['ID'].'(?),';
echo ' NAME: '.$course['NAME'].'(?)<br/>';
echo 'ATTRIBUTE NAME: ???,';
echo ' ATTRIBUTE VALUE: ???<hr/>'; // not sure how to pull those results
$i++;
}
所以我试图从标签item 中获取id 和name,并从标签attribute 中的第一个元素item 中获取name 和value...
有什么想法吗?
更新: 注意:course['ID'] 和 course['NAME'] 没有回显任何内容,但是当我使用 course['ITEM'] 或 course['ATTRIBUTE'] 时,它会回显标签内的任何内容 item 或attribute ex:<item> this </item>,而我想得到的是:<item THIS="this" />
【问题讨论】:
-
并非如此,XMLReader 是更现代、更简单的方法。
-
不是最快的一个...当我使用 XMLReader 解析一个大的 xml 文件时,加载页面需要 15 秒
-
所以你真的对 cdata 不感兴趣,只对元素及其属性感兴趣?
-
@user3050478 完全正确!