Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 重写SimpleXMLElement::_toString并强制转换为string_Php_Simplexml - Fatal编程技术网

Php 重写SimpleXMLElement::_toString并强制转换为string

Php 重写SimpleXMLElement::_toString并强制转换为string,php,simplexml,Php,Simplexml,我想将一些XML读入SimpleXMLElement,然后通过将元素转换为字符串,将元素值用作字符串。对于每个SimpleXMLELement,我希望在返回元素字符串之前更改它。我希望在一个地方执行操作,而不是在访问元素的任何地方重复操作 我的第一个想法是重写SimpleXMLElement_uuutoString,但这似乎只是通过print调用的,而不是通过(string)强制转换为string 是否有其他我应该覆盖的内容,或者是否有更好的方法 <?php $string_xml = "

我想将一些XML读入SimpleXMLElement,然后通过将元素转换为字符串,将元素值用作字符串。对于每个SimpleXMLELement,我希望在返回元素字符串之前更改它。我希望在一个地方执行操作,而不是在访问元素的任何地方重复操作

我的第一个想法是重写SimpleXMLElement_uuutoString,但这似乎只是通过print调用的,而不是通过(string)强制转换为string

是否有其他我应该覆盖的内容,或者是否有更好的方法

<?php
$string_xml = "<?xml version='1.0' encoding='UTF-8'?>
<foo>
    <bar>baz</bar>
</foo>";

$xml = simplexml_load_string($string_xml, 'ToStringTest');
print "cast ";
$s = (string)$xml->bar;
print $s;
// "cast baz" is printed
print "\nprint ";
print $xml->bar;
// "print uses __toStringbazfoo" is printed

class ToStringTest extends SimpleXMLElement
{   
    public function __toString()
    {   
        print "uses __toString";
        return parent::__toString() . 'foo';
    }
}

是否尝试交换simplexml\u load\u字符串的类定义和用法

<?php
$string_xml = "<?xml version='1.0' encoding='UTF-8'?>
<foo>
    <bar>baz</bar>
</foo>";

class ToStringTest extends SimpleXMLElement
{   
    public function __toString()
    {   
        print "uses __toString";
        return parent::__toString() . 'foo';
    }
}

$xml = simplexml_load_string($string_xml, 'ToStringTest');
print "cast ";
$s = (string)$xml->bar;
print $s;
// "cast baz" is printed
print "\nprint ";
print $xml->bar;
// "print uses __toStringbazfoo" is printed

SimpleXML的逻辑是用C编写的,而不是用PHP编写的,因此可能不会调用PHP函数来处理类似的事情。与其重载
\uu toString()
,不如添加一个额外的方法,比如
->getManipulatedString()
。理想情况下,我希望避免这种方法,除了构造SimpleXMLElement之外,我希望应用程序的其余部分能够像对待任何其他SimpleXMLElement一样对待它。没有更好的建议,如果这是一个答案,我会接受它。谢谢,但这里不是这样的,PHP不是这样工作的,这也不能解释为什么打印工作和(字符串)不工作。