I have the PHP 8 code:
$test = '<?xml version="1.0" encoding="utf-8"?>
<FDL>
<TITLE>
<Title>Test element</Title>
</TITLE>
</FDL>';
$test_obj = simplexml_load_string($test);
var_dump($test_obj->TITLE->Title);
var_dump($test_obj->TITLE->Title->children);
Which returns:
object(SimpleXMLElement)#5 (1) {
[
0
]=>
string(12) "Test element"
}
object(SimpleXMLElement)#3 (0) {}
And that is my problem - the $test_obj->TITLE->Title
and $test_obj->TITLE->Title->children
return objects (SimpleXMLElement), but I am interested in the string-type content of this element? How can I access it? Of course, if I am using echo (instead of var_dump) in my previous code then I can see the string type content, but under the cover - this is not string type variable and it does not behave as string type variable in the further PHP code where I am trying to use it.
So - how to the the string type content from the SimpleXMLElement?
The way to do this is to "cast" the variable to a string, using the standard PHP syntax (string)$someVariableOrExpression
, which is defined specially on the SimpleXMLElement class :
$test = '<?xml version="1.0" encoding="utf-8"?>
<FDL>
<TITLE>
<Title>Test element</Title>
</TITLE>
</FDL>';
$test_obj = simplexml_load_string($test);
$content = (string)$test_obj->TITLE->Title;
var_dump($content);
# string(12) "Test element"
This is actually what lets echo
work under the hood: it first converts whatever arguments you give it to strings, which tells the SimpleXMLElement object to return its string content.
This is also shown in some of the SimpleXML examples in the PHP manual .
You could use xpath instead of dot notation:
$target = (string)$test_obj->xpath("//TITLE/Title")[0];
echo $target,": ", gettype($target);
Output:
Test element: string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.