<?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. Python实现装饰模式的一段代码

    # 实现装饰模式的一段代码 import functools def log(func): @functools.wraps(func) def wrapper(*args,**kw): print( ...

  2. rabbitmq启动异常之error,{not_a_dets_file recovery.dets

    中午,公司群里面测试人员@笔者说,早上测试服务器异常,MQ起不来,重启os了也起不来,报错,上去看下了早上又因为内存oom被内核killed了,启动了下,确实启动报错,erl vm进程起来了,但是be ...

  3. 玩转Docker之常用命令篇(三)

    首先我们来解决一个小问题,使用docker每次都要用sudo,为了让非root用户使用docker,可将当前用户添加到docker用户组: sudo groupadd docker sudo gpas ...

  4. js的动态加载、缓存、更新以及复用(二)

    上一篇发出来后得到了很多回复,在此首先感谢大家的热情捧场!有的推荐第三方框架,比如 In.js.requrieJS.sea.js.lab.js等.这个开阔了眼界,以前只知道sea.js,省去了自己搜索 ...

  5. Fixed Responsive Nav – 响应式的单页网站导航插件

    Fixed Responsive Nav 是一个响应式的,固定的,触摸友好的单页网站导航插件,响应式导航,流畅的动画滚动.该项目采用渐进增强构建,支持工作在 IE6 及以上版本的浏览器. 你可以给导航 ...

  6. 25个有用的和方便的 WordPress 速查手册

    如果你是 WordPress 开发人员,下载一些方便的 WordPress 备忘单可以在你需要的时候快速查找.下面这个列表,我们已经列出了25个有用的和方便的 WordPress 速查手册,赶紧收藏吧 ...

  7. 请使用java来构造和遍历二叉树?

    [分析] 二叉树的结构:根节点.左子树.右子树.其中左子树的值必须小于根节点,右子树的值必须大于根节点.构造这种树结构,就是创建一个类,并提供一个方法,当给定一个值时,它能够自动创建节点并自动挂到二叉 ...

  8. php扩展php_curl windows 安装问题

    关于安装php扩展php_curl 出现的提示错误,导致php_curl无法安装 apache 错误日志: PHP Warning: PHP Startup: in Unknown on line 0 ...

  9. 浅析css布局模型2

    上节对整个布局模型进行了概述,这节先谈一下布局模型的几个属性. z-index属性 该属性是检索或设置对象的层叠顺序,默认值为auto,遵循其父对象的定位. 并级的对象,该属性的值越大,则被层叠在最上 ...

  10. arcgis批量处理mxd定义服务中的路径

     >>> from arcpy import env... env.workspace=r"c:\165mxd"... out = r"c:\166mx ...