连字符在 PHP 变量名中无效。我建议用下划线代替它们,如$new_data
and $data_content
。最后,您初始化$xml
,但后来尝试使用未知变量$xml_object
。将这些更改为$xml
.
$input = "file1.xml";
$xml = simplexml_load_file($input);
$data_content = $xml->data->getAssetResponse->content;
$new_data = str_replace("text", "REPLACED STUFF", (string)$data_content);
$xml->data->getAssetResponse->content = $new_data;
print $xml->asXML();
// Outputs:
<response>
<statusCode>200</statusCode>
<statusText>OK</statusText>
<data>
<getAssetResponse>
<assetId>89898</assetId>
<content> some text with HTML content some REPLACED STUFF with HTML content </content>
</getAssetResponse>
</data>
</response>
来自 PHP 文档:
变量名称遵循与 PHP 中其他标签相同的规则。有效的变量名称以字母或下划线开头,后跟任意数量的字母、数字或下划线。作为正则表达式,它会这样表达:'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'