simplexml_load_string解析的问题

在微信公众平台开发中,发现一个simplexml_load_string解析后的问题。

分析

微信给的PHP官方示例,代码如下:

$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);

这里假设fromUsername = 'openid';
后面往数据库里插入fromUsername数据的时候报错,提示openid字段不存在。

奇了怪了,openid明明是值,怎么会提示字段不存在呢。

在数据库插入前,打印fromUsername,输出如下:

SimpleXMLElement Object ( [0] => openid )

这里居然还是个对象,而不是字符串!!!

搜索一番,在php手册找到个同样的问题。

There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine under PHP 5.2.6 

The key is noted above example #6 here: 
http://uk2.php.net/manual/en/simplexml.examples.php 

"To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object." 

If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the string content of the element. So some functions, including print_r(), might not show what you expect. But if you explicitly cast to a string, you get the whole content. 

Text1 & XML entities'); 
print_r($xml); 
/* 
SimpleXMLElement Object 
( 
    [0] => Text1 & XML entities 
) 
*/ 

$xml2 = simplexml_load_string(''); 
print_r($xml2); 
/* 
SimpleXMLElement Object 
( 
) 
*/ 
// Where's my CDATA? 

// Let's try explicit casts 
print_r( (string)$xml ); 
print_r( (string)$xml2 ); 
/* 
Text1 & XML entities 
Text2 & raw data 
*/ 
// Much better 
?>

解决方法

同样的是在php手册下面找到解决方法,代码如下:

$postObj = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj['FromUserName'];
$toUsername = $postObj['ToUserName'];
$keyword = trim($postObj['Content']);

将对象转为数组后,报错消失。

标签: none

添加新评论