<?php

error_reporting(E_ALL);

/* Data can be send to coroutines using `$coroutine->send($data)`. The sent data will then
* be the result of the `yield` expression. Thus it can be received using a code like
* `$data = yield;`.
*/ /* What we're building in this script is a coroutine-based streaming XML parser. The PHP
* extension for parsing streamed XML is xml_parser. It is used by defining a set of
* callback functions for various events (like start tag, end tag, content).
*
* This event model makes the parsing process very complicated, because you basically
* have to implement your own state machine (which is a lot of boilerplate code the
* more complicated the XML gets).
*
* To solve this problem, we build a wrapper (the following function), which redirects
* the events to a coroutine ($target). This is done simply using
* `$target->send([$eventName, $data])`.
*/
function streamingXMLParser($target) {
$xmlParser = xml_parser_create();
xml_set_element_handler(
$xmlParser,
function ($xmlParser, $name, array $attributes) use ($target) {
$target->send(['start', [$name, $attributes]]);
},
function ($xmlParser, $name) use ($target) {
$target->send(['end', $name]);
}
);
xml_set_character_data_handler(
$xmlParser,
function ($xmlParser, $text) use ($target) {
$target->send(['text', $text]);
}
); while ($data = yield) {
if (!xml_parse($xmlParser, $data)) {
throw new Exception(sprintf(
'XML error "%s" on line %d',
xml_error_string(xml_get_error_code($xmlParser)),
xml_get_current_line_number($xmlParser)
));
}
} xml_parser_free($xmlParser);
} /* Inside the target coroutine the actual parsing happens. The events are received
* using `list($event, $data) = yield`. The main advantage that coroutines bring
* here is that you can fetch the events in nested loops. This way you are implicitly
* building a state machine (but the state is managed by PHP, not you!)
*
* This particular coroutine parses bus location data (for samples scroll down). The
* result is passed to another $target coroutine.
*/
function busXMLParser($target) {
while (true) {
list($event, $data) = yield;
if ($event == 'start' && $data[0] == 'BUS') {
$dict = [];
$content = '';
while (true) {
list($event, $data) = yield;
if ($event == 'start') {
$content = '';
} elseif ($event == 'text') {
$content .= $data;
} elseif ($event == 'end') {
if ($data == 'BUS') {
$target->send($dict);
break;
} $dict[strtolower($data)] = $content;
}
}
}
}
} /* This coroutine prints out the info it receives from the bus XML parser. */
function busLocationPrinter() {
while (true) {
$data = yield;
echo "Bus $data[id] is currently at $data[latitude]/$data[longitude]\n";
}
} /* Here we are building up a coroutine pipeline. You should read this as:
* The streaming XML parser is passing data to the bus XML parser, which
* is passing data to the bus location printer.
*/
$parser = streamingXMLParser(busXMLParser(busLocationPrinter())); /* I don't have access to a real bus location API, so I'll just stream some
* fictional sample data */
$parser->send('<?xml version="1.0"?><buses>');
while (true) {
sleep(1);
$parser->send(sprintf(
'<bus><id>%d</id><latitude>%f</latitude><longitude>%f</longitude></bus>',
mt_rand(1, 1000), lcg_value(), lcg_value()
));
} /* If your head is buzzing now, that's a good thing :P */

A coroutine example: Streaming XML parsing using xml_parser的更多相关文章

  1. Dreamweaver无法启动:xml parsing fatal error..Designer.xml错误解决方法

    xml parsing fatal error:Invalid document structure,line:1,file:C:\Documents and Settings\Administrat ...

  2. XML Parsing Error: no element found Location: moz-nullprincipal:{23686e7a-652b-4348-92f4-7fb3575179ed} Line Number 1, Column 1:^

    “Hi Insus.NET, 我有参考你下午发布的一篇<jQuery.Ajax()执行WCF Service的方法>http://www.cnblogs.com/insus/p/37278 ...

  3. 解决org.apache.jasper.JasperException: org.apache.jasper.JasperException: XML parsing error on file org.apache.tomcat.util.scan.MergedWebXml

    1.解决办法整个项目建立时采用utf-8编码,包括代码.jsp.配置文件 2.并用最新的tomcat7.0.75 相关链接: http://ask.csdn.net/questions/223650

  4. Parsing XML in J2ME

    sun的原文,原文地址是http://developers.sun.com/mobility/midp/articles/parsingxml/. by Jonathan KnudsenMarch 7 ...

  5. 【Java】Java XML 技术专题

    XML 基础教程 XML 和 Java 技术 Java XML文档模型 JAXP(Java API for XML Parsing) StAX(Streaming API for XML) XJ(XM ...

  6. iphone Dev 开发实例8: Parsing an RSS Feed Using NSXMLParser

    From : http://useyourloaf.com/blog/2010/10/16/parsing-an-rss-feed-using-nsxmlparser.html Structure o ...

  7. php判断字符串是不是xml格式并解析

    最近遇到要要判断一个字符串是不是xml格式,网上找到一段代码,试了一下,完全可行 /**      * 解析XML格式的字符串      *      * @param string $str     ...

  8. Java解析XML文档(简单实例)——dom解析xml

      一.前言 用Java解析XML文档,最常用的有两种方法:使用基于事件的XML简单API(Simple API for XML)称为SAX和基于树和节点的文档对象模型(Document Object ...

  9. javascript-处理XML

    /** * Created by Administrator on 2015/4/4. */ var XmlUtil=(function () { var createDocument= functi ...

随机推荐

  1. 【转】nginx优化 突破十万并发

    一.一般来说nginx 配置文件中对优化比较有作用的为以下几项: 1. worker_processes 8; nginx 进程数,建议按照cpu 数目来指定,一般为它的倍数 (如,2个四核的cpu计 ...

  2. Java的对象初始化过程

    成员变量(字段)初始化顺序 在一个类里初始化的顺序是由成员变量在类里面的定义的顺序来决定的.即使成员变量大量散布于类的各个方法定义的中间,那些成员变量仍会在调用任何方法之前得以初始化,甚至在构造函数调 ...

  3. angular学习的一些小笔记(中)之基础ng指令

    一.布尔属性指令: ng-disabled:就是ng-disabled=true-->就指向不可用 <!doctype html> <html ng-app="&qu ...

  4. 15款美丽的设备模板,帮助展示你的 APP

    有什么更好的方式来显示您的应用程序的外观和感觉呢?你看了这些设计示例之后就会有灵感了.无论是在 iPhone,iPad,Android,还是在桌面应用程序或网站,这些设计都增加了一些视觉上的吸引力,并 ...

  5. array's filter

    var arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, { }, { id: null }, { id: NaN ...

  6. CSS3 一、文本阴影text-shadow属性

    文本阴影text-shadow属性特效: 1.右下角阴影,左下角阴影,左上角阴影,右上角阴影 <!DOCTYPE html> <html lang="en"> ...

  7. AdaBoost算法实现

    # -*- coding: utf-8 -*- # -------------------------------------------------------------------------- ...

  8. Snort - manual 笔记(一)

    Chapter 1 Snort Overview This manual is based on Writing Snort Rules by Martin Roesch and further wo ...

  9. Snort - manual 笔记(四)

    1.7 Basic Output Snort可以做很多任务, 并且在任务完成后输出很多有用的统计信息. 一些不用说明就可以看懂, 其他的总结在这里, 不过只是一些基本的 1.7.1 Timing St ...

  10. 原创:phoenix4.6.0连接hbase1.1.2(不使用phoenix-4.6.0-HBase-1.1-client.jar)

    官网上面的例子是在phoenix-4.6.0-HBase-1.1-client.jar完成的,这个jar包含了phoenix4.6连接hbase1.1.2所有的依赖,真是包罗万象(里面竟然还包括了se ...