PHP retrieve xml node value with simplexml [duplicate]
Possible Duplicate:
PHP SimpleXML get innerXML
I've seen others questions related to simplexml and node value but couldn't find an answer to my problem.
I have a PHP var which contains an xml document formed like that :
<div id="container">
<div id="header"></div>
<div id="main">
##CONTENTS## cd <strong>dscsdcsd</strong> sdcsc
<div>my content here</div>
<span>and there</span>
</div>
<div id="footer"> </div>
</div>
I want to retrieve the node value. But with the following code, I also retrieve the tag :
$xml = simplexml_load_string($_POST['newsletter_body']);
$att = 'id';
foreach ($xml->children() as $el) {
if($el->attributes()->$att == 'main') {
$body_content = $el->asXml();
}
}
Could someone开发者_StackOverflow tell me how to get only node value (without using xpath)?
To be clear, now I get :
<div id="main">
##CONTENTS## cd <strong>dscsdcsd</strong> sdcsc
<div>my content here</div>
<span>and there</span>
</div>
And I just want :
##CONTENTS## cd <strong>dscsdcsd</strong> sdcsc
<div>my content here</div>
<span>and there</span>
Many thanks
As suggested by @Tomalak, this is a duplicate of Stackoverflow: PHP SimpleXML get innerXML and you cannot do better than suggested with simplexml API.
function simplexml_innerXML($xml)
{
$content="";
foreach($node->children() as $child)
$content .= $child->asXml();
return $content;
}
In your code, replace $body_content = $el->asXml();
with $body_content = simplexml_innerXML($el);
However, you could also switch to another API that ofers distinction between innerXML
(what you are looking for) and outerXML
(what you get for now). Microsoft Dom libary offers this distinction but unfortunately PHP DOM doesn't.
I found that PHP XMLReader API
offers this distintion. See readInnerXML(). Though this API has quite a different approach to processing XML. Try it.
Finally, I would stress that XML is not meant to extract data as subtrees but rather as value. That's why you running into trouble finding the right API. It would be more 'standard' to store HTML subtree as a value (and escape all tags) rather than XML subtree. Also beware that some HTML synthax are not always XML compatible ( i.e. <br> vs ,<br/>
). Anyway in practice, you approach is definitely more convenient for editing the xml file.
精彩评论