Parsing xml-like data
I have a string with xml-like data:
<header>Article header</header>
<description>This article is about you</description>
<text>some <b>html</b> text</text>
I need to parse 开发者_运维技巧it into variables/object/array "header", "description", "text".
What is the best way to do this? I tried $vars = simplexml_load_string($content)
, but it does not work, because it is not 100% pure xml (no <?xml...
).
preg_match
? Is it the only way?Your XML string looks like (though may or may not be) an XML document fragment. PHP can work with this using the DOMDocumentFragment
class.
$doc = new DOMDocument;
$frag = $doc->createDocumentFragment();
$frag->appendXML($content);
$parsed = array();
foreach ($frag->childNodes as $element) {
if ($element->nodeType === XML_ELEMENT_NODE) {
$parsed[$element->nodeName] = $element->textContent;
}
}
echo $parsed['description']; // This article is about you
With a string like that, simlexml_load_string should work.
Because of the 3rd tag, if you try to get that it will fail, and not return the correct value (because there is a sub part within the tag.
Try something like this, which might work for you:
$xml = simplexml_load_string($content)
$text = $xml->text->asXML();
You should also take a look at this documentation: http://www.php.net/manual/en/simplexmlelement.asxml.php. They also do the same thing with the string. You might wanna use this option instead of simplexml_load_string
too
$xml = new SimpleXMLElement($string);
精彩评论