SimpleXml to string

2019-03-08 02:54发布

Is there any function that makes string from PHP SimpleXMLElement?

7条回答
2楼-- · 2019-03-08 03:12

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'

查看更多
Root(大扎)
3楼-- · 2019-03-08 03:18

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);.

查看更多
冷血范
4楼-- · 2019-03-08 03:31

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();
?>
查看更多
闹够了就滚
5楼-- · 2019-03-08 03:31

This is an old post, but my findings might help someone.

Probably depending on the xml feed you may/may not need to use __toString(); I had to use the __toString() otherwise it is returning the string inside an SimpleXMLElement. Maybe I need to drill down the object further ...

查看更多
【Aperson】
6楼-- · 2019-03-08 03:32

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();
查看更多
Summer. ? 凉城
7楼-- · 2019-03-08 03:36

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()));
查看更多
登录 后发表回答