XML parsing: Uncaught TypeError: Object [object Ob

2019-08-30 00:43发布

问题:

$results = simplexml_load_string($results);
foreach($results as $result){
    $result_title = $result->label;
    $result_title = preg_replace('#[^a-zA-Z]+Extra Title#', '', $result_title);
    $result_title = ltrim($result_title);

The first preg_replace gets rid of a pattern at the end of the $result->label (which var_dumps as an XML object) and outputs, not an XML object, but a string.

This is surprising because I thought that preg_replace would only work on strings and not the XML object. A var_dump of the $result reveals:

object(SimpleXMLElement)#1003 (1) { [0]=> string(31) " Some Text > Extra Title" }

Note the extra white space before 'Some Text'. The second ltrim($result_title);, however, causes this error:

Uncaught TypeError: Object [object Object] has no method 'suggest'

So what am I dealing with? A string or an object? And how do I trim the whitespace?

Trying a preg_replace for the first whitespace also outputs the same error as above.

$result_title = preg_replace('/\s/', '', $result_title, 1);