Is there any function that makes string from PHP SimpleXMLElement?
8 Answers
You can use the SimpleXMLElement::asXML() method to accomplish this:
$string = "<element><child>Hello World</child></element>"; $xml = new SimpleXMLElement($string); // The entire XML tree as a string: // "<element><child>Hello World</child></element>" $xml->asXML(); // Just the child node as a string: // "<child>Hello World</child>" $xml->child->asXML(); 4 Comments
$string = $xml->child->__toString();You can use casting:
<?php $string = "<element><child>Hello World</child></element>"; $xml = new SimpleXMLElement($string); $text = (string)$xml->child; $text will be 'Hello World'
1 Comment
You can use the asXML method as:
<?php // string to SimpleXMLElement $xml = new SimpleXMLElement($string); // make any changes. .... // convert the SimpleXMLElement back to string. $newString = $xml->asXML(); ?> Comments
Actually asXML() converts the string into xml as it name says:
<id>5</id> This will display normally on a web page but it will cause problems when you matching values with something else.
You may use strip_tags function to get real value of the field like:
$newString = strip_tags($xml->asXML()); PS: if you are working with integers or floating numbers, you need to convert it into integer with intval() or floatval().
$newNumber = intval(strip_tags($xml->asXML())); Comments
You can use ->child to get a child element named child.
This element will contain the text of the child element.
But if you try var_dump() on that variable, you will see it is not actually a PHP string.
The easiest way around this is to perform a strval(xml->child); That will convert it to an actual PHP string.
This is useful when debugging when looping your XML and using var_dump() to check the result.
So $s = strval($xml->child);.
Comments
Here is a function I wrote to solve this issue (assuming tag has no attributes). This function will keep HTML formatting in the node:
function getAsXMLContent($xmlElement) { $content=$xmlElement->asXML(); $end=strpos($content,'>'); if ($end!==false) { $tag=substr($content, 1, $end-1); return str_replace(array('<'.$tag.'>', '</'.$tag.'>'), '', $content); } else return ''; } $string = "<element><child>Hello World</child></element>"; $xml = new SimpleXMLElement($string); echo getAsXMLContent($xml->child); // prints Hello World Comments
Sometimes you can simply typecast:
// this is the value of my $xml object(SimpleXMLElement)#10227 (1) { [0]=> string(2) "en" } $s = (string) $xml; // returns "en"; 1 Comment
$xmlitem->description. Thanks.