PHP SimpleXML对象中消失的属性?

hea*_*der 7 php xml json object simplexml

我需要返回一个转换为JSON对象的SimpleXML对象,以便在JavaScript中使用它.问题是任何具有值的对象都没有属性.

举个例子:

<customer editable="true" maxChars="9" valueType="numeric">69236</customer>
Run Code Online (Sandbox Code Playgroud)

变为SimpleXML对象:

"customer":"69236"
Run Code Online (Sandbox Code Playgroud)

@attributes对象在哪里?

rya*_*ell 8

这让我疯了几次.当SimpleXML遇到只有文本值的节点时,它会删除所有属性.我的解决方法是在使用SimpleXML解析之前修改XML.使用一些正则表达式,您可以创建包含实际文本值的子节点.例如,在您的情况下,您可以将XML更改为:

<customer editable="true" maxChars="9" valueType="numeric"><value>69236<value></customer>
Run Code Online (Sandbox Code Playgroud)

假设您的XML字符串在$ str中的一些示例代码:

$str = preg_replace('/<customer ([^>]*)>([^<>]*)<\/customer>/i', '<customer $1><value>$2</value></customer>', $str);
$xml = @simplexml_load_string($str);
Run Code Online (Sandbox Code Playgroud)

这将保留属性并将文本值嵌套在子节点中.


小智 5

我意识到这是一个老帖子,但万一它证明有用.以下扩展@ ryanmcdonnell的解决方案,适用于任何标签而不是硬编码标签.希望它可以帮助某人.

$str = preg_replace('/<([^ ]+) ([^>]*)>([^<>]*)<\/\\1>/i', '<$1 $2><value>$3</value></$1>', $result);
Run Code Online (Sandbox Code Playgroud)

主要的不同之处在于它取代/<customer/<([^ ]+),然后</customer></\\1>

它告诉它将搜索的那一部分与模式中的第一个元素相匹配.

然后,它只是调整占位符($1,$2,$3)考虑到一个事实,即有三子匹配的现在而不是两个.


Wil*_*eth -1

下面是一些用于迭代属性并构造 JSON 的代码。如果支持,一个或多个客户。

如果您的 XML 看起来像这样(或只是一个客户)

<xml>
<customer editable="true" maxChars="9" valueType="numeric">69236</customer>
<customer editable="true" maxChars="9" valueType="numeric">12345</customer>
<customer editable="true" maxChars="9" valueType="numeric">67890</customer>
</xml>
Run Code Online (Sandbox Code Playgroud)

像这样迭代它。

try {
    $xml = simplexml_load_file( "customer.xml" );

    // Find the customer
    $result = $xml->xpath('/xml/customer');

    $bFirstElement = true;
    echo     "var customers  = {\r\n";
    while(list( , $node) = each($result)) {
        if( $bFirstElement ) {
            echo "'". $node."':{\r\n";
            $bFirstElement = false;
        } else {
            echo ",\r\n'". $node."':{\r\n";
        }

        $bFirstAtt = true;
        foreach($node->attributes() as $a => $b) { 
            if( $bFirstAtt ) {
                echo "\t".$a.":'".$b."'";
                $bFirstAtt = false;
            } else {
                echo ",\r\n\t".$a.":'".$b."'";
            }
        }
        echo "}";
    }
    echo "\r\n};\r\n";
} catch( Exception $e ) {
    echo "Exception on line ".$e->getLine()." of file ".$e->getFile()." : ".$e->getMessage()."<br/>";
}
Run Code Online (Sandbox Code Playgroud)

生成这样的 JSON 结构

var customers  = {
'69236':{
    editable:'true',
    maxChars:'9',
    valueType:'numeric'},
'12345':{
    editable:'true',
    maxChars:'9',
    valueType:'numeric'},
'67890':{
    editable:'true',
    maxChars:'9',
    valueType:'numeric'}
};
Run Code Online (Sandbox Code Playgroud)

最后,在您的脚本中,像这样访问属性

WScript.Echo( customers["12345"].editable );
Run Code Online (Sandbox Code Playgroud)

祝你好运