Forcing a SimpleXML Object to a string, regardless

2019-01-01 13:34发布

Let's say I have some XML like this

<channel>
  <item>
    <title>This is title 1</title>
  </item>
</channel>

The code below does what I want in that it outputs the title as a string

$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;

Here's my problem. The code below doesn't treat the title as a string in that context so I end up with a SimpleXML object in the array instead of a string.

$foo = array( $xml->channel->item->title );

I've been working around it like this

$foo = array( sprintf("%s",$xml->channel->item->title) );

but that seems ugly.

What's the best way to force a SimpleXML object to a string, regardless of context?

10条回答
与君花间醉酒
2楼-- · 2019-01-01 13:46

The accepted answer actually returns an array containing a string, which isn't exactly what OP requested (a string). To expand on that answer, use:

$foo = [ (string) $xml->channel->item->title ][0];

Which returns the single element of the array, a string.

查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 13:47

Another ugly way to do it:

$foo = array( $xml->channel->item->title."" );

It works, but it's not pretty.

查看更多
时光乱了年华
4楼-- · 2019-01-01 13:47

There is native SimpleXML method SimpleXMLElement::asXML Depending on parameter it writes SimpleXMLElement to xml 1.0 file, Yes

$get_file= read file from path;
$itrate1=$get_file->node;
$html  = $itrate1->richcontent->html;


echo  $itrate1->richcontent->html->body->asXML();
 print_r((string) $itrate1->richcontent->html->body->asXML());
查看更多
看风景的人
5楼-- · 2019-01-01 13:51

You can use the PHP function

strval();

This function returns the string values of the parameter passed to it.

查看更多
看风景的人
6楼-- · 2019-01-01 13:52

To get XML data into a php array you do this:

// this gets all the outer levels into an associative php array
$header = array();
foreach($xml->children() as $child)
{
  $header[$child->getName()] = sprintf("%s", $child); 
}
echo "<pre>\n";
print_r($header);
echo "</pre>";

To get a childs child then just do this:

$data = array();
foreach($xml->data->children() as $child)
{
  $header[$child->getName()] = sprintf("%s", $child); 
}
echo "<pre>\n";
print_r($data);
echo "</pre>";

You can expand $xml-> through each level until you get what you want You can also put all the nodes into one array without the levels or just about any other way you want it.

查看更多
时光乱了年华
7楼-- · 2019-01-01 13:53

Typecast the SimpleXMLObject to a string:

$foo = array( (string) $xml->channel->item->title );

The above code internally calls __toString() on the SimpleXMLObject. This method is not publicly available, as it interferes with the mapping scheme of the SimpleXMLObject, but it can still be invoked in the above manner.

查看更多
登录 后发表回答