php 读取mysql 返回xml_PHP读取XML格式文件的方法总结

本文实例总结了PHP读取XML格式文件的方法。分享给大家供大家参考,具体如下:

books.xml文件:

Jack Herrington

PHP Hacks

O'Reilly

Jack Herrington

Podcasting Hacks

O'Reilly

1.DOMDocument方法

$doc = new DOMDocument();

$doc->load( 'books.xml' );

$books = $doc->getElementsByTagName( "book" );

foreach( $books as $book )

{

$authors = $book->getElementsByTagName( "author" );

$author = $authors->item(0)->nodeValue;

$publishers = $book->getElementsByTagName( "publisher" );

$publisher = $publishers->item(0)->nodeValue;

$titles = $book->getElementsByTagName( "title" );

$title = $titles->item(0)->nodeValue;

echo "$title - $author - $publisher\n";

echo "
";

}

?>

2.用 SAX 解析器读取 XML:

$g_books = array();

$g_elem = null;

function startElement( $parser, $name, $attrs )

{

global $g_books, $g_elem;

if ( $name == 'BOOK' ) $g_books []= array();

$g_elem = $name;

}

function endElement( $parser, $name )

{

global $g_elem;

$g_elem = null;

}

function textData( $parser, $text )

{

global $g_books, $g_elem;

if ( $g_elem == 'AUTHOR' ||

$g_elem == 'PUBLISHER' ||

$g_elem == 'TITLE' )

{

$g_books[ count( $g_books ) - 1 ][ $g_elem ] = $text;

}

}

$parser = xml_parser_create();

xml_set_element_handler( $parser, "startElement", "endElement" );

xml_set_character_data_handler( $parser, "textData" );

$f = fopen( 'books.xml', 'r' );

while( $data = fread( $f, 4096 ) )

{

xml_parse( $parser, $data );

}

xml_parser_free( $parser );

foreach( $g_books as $book )

{

echo $book['TITLE']." - ".$book['AUTHOR']." - ";

echo $book['PUBLISHER']."\n";

}

?>

3.用正则表达式解析 XML:

$xml = "";

$f = fopen( 'books.xml', 'r' );

while( $data = fread( $f, 4096 ) ) {

$xml .= $data;

}

fclose( $f );

preg_match_all( "/\(.*?)\/s", $xml, $bookblocks );

foreach( $bookblocks[1] as $block )

{

preg_match_all( "/\(.*?)\/", $block, $author );

preg_match_all( "/\

(.*?)\/", $block, $title );

preg_match_all( "/\(.*?)\/", $block, $publisher );

echo( $title[1][0]." - ".$author[1][0]." - ".$publisher[1][0]."\n" );

}

?>

4.解析XML到数组

$data = "简单的XML数据";

$parser = xml_parser_create(); //创建解析器

xml_parse_into_struct($parser, $data, $values, $index); //解析到数组

xml_parser_free($parser); //释放资源

//显示数组结构

echo "\n索引数组\n";

print_r($index);

echo "\n数据数组\n";

print_r($values);

?>

5.检查XML是否有效

//创建XML解析器

$xml_parser = xml_parser_create();

//使用大小写折叠来保证能在元素数组中找到这些元素名称

xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);

//读取XML文件

$xmlfile = "bb.xml";

if (!($fp = fopen($xmlfile, "r")))

{

die("无法读取XML文件$xmlfile");

}

//解析XML文件

$has_error = false; //标志位

while ($data = fread($fp, 4096))

{

//循环地读入XML文档,只到文档的EOF,同时停止解析

if (!xml_parse($xml_parser, $data, feof($fp)))

{

$has_error = true;

break;

}

}

if($has_error)

{

echo "该XML文档是错误的!
";

//输出错误行,列及其错误信息

$error_line = xml_get_current_line_number($xml_parser);

$error_row = xml_get_current_column_number($xml_parser);

$error_string = xml_error_string(xml_get_error_code($xml_parser));

$message = sprintf("[第%d行,%d列]:%s",

$error_line,

$error_row,

$error_string);

echo $message;

}

else

{

echo "该XML文档是结构良好的。";

}

//关闭XML解析器指针,释放资源

xml_parser_free($xml_parser);

?>

6.可用于精确的读取XML

test.xml

100

123456

20040605

153020

1

1

010

北京

010

北京

0

0

15933626501

8

5618常年供应苗木,品种有玉兰、黄叶杨等。联系人:张三,电话:1234567890。

100

9588

test.php:

$myData = array();

$file = file_get_contents("test.xml");

if(strpos($file, '<?xml ') > -1) {

try {

//加载解析xml

$xml = simplexml_load_string($file);

if($xml) {

//echo $this->result;

//获取节点值

$CONNECT_ID = $xml->CONNECT_ID;

$MO_MESSAGE_ID = $xml->MO_MESSAGE_ID;

$RECEIVE_DATE = $xml->RECEIVE_DATE;

$RECEIVE_TIME = $xml->RECEIVE_TIME;

$GATEWAY_ID = $xml->GATEWAY_ID;

$VALID = $xml->VALID;

$CITY_CODE = $xml->CITY_CODE;

$CITY_NAME = $xml->CITY_NAME;

$STATE_CODE = $xml->CITY_CODE;

$STATE_NAME = $xml->STATE_NAME;

$TP_PID = $xml->TP_PID;

$TP_UDHI = $xml->TP_UDHI;

$MSISDN = $xml->MSISDN;

$MESSAGE_TYPE = $xml->MESSAGE_TYPE;

$MESSAGE = $xml->MESSAGE;//短信

$LONG_CODE = $xml->LONG_CODE;

$SERVICE_CODE = $xml->SERVICE_CODE;

preg_match("/(561)\d{1,2}/", $MESSAGE, $code);

switch($code[0]) {

case 5618 :

$myData[message] = $MESSAGE;

break;

default :

$myData[] = '没有短消息。';

break;

}

} else {

echo "加载xml文件错误。";

}

} catch(exception $e){

print_r($e);

}

} else {

echo "没有该XML文件。";

}

echo "

";

print_r($myData);

echo "


";

echo $myData[message];

?>

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

希望本文所述对大家PHP程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以使用Jackson XML库来读取XML配置文件中的JSON数据,并使用Spring Data JDBC来连接数据库。 首先,需要在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.12.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> ``` 接下来,在application.properties或application.yml文件中配置数据库连接信息: ```yml spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root ``` 然后,在读取XML配置文件中的JSON文件时,可以使用以下代码: ```java @Autowired private ResourceLoader resourceLoader; public void readJsonFromXml() throws IOException { Resource resource = resourceLoader.getResource("classpath:config.xml"); XmlMapper xmlMapper = new XmlMapper(); JsonNode jsonNode = xmlMapper.readValue(resource.getFile(), JsonNode.class); String url = jsonNode.get("database").get("url").asText(); String username = jsonNode.get("database").get("username").asText(); String password = jsonNode.get("database").get("password").asText(); // 使用JDBC连接数据库 } ``` 其中,config.xml文件的内容如下: ```xml <config> <database> <url>{"url":"jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai"}</url> <username>{"username":"root"}</username> <password>{"password":"root"}</password> </database> </config> ``` 通过以上步骤,就可以通过读取XML配置文件中的JSON文件来连接数据库了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值