PHP : XML 解析并返回 XML


php : xml parse and return xml

XML 解析不起作用

<?php 
$input = "file1.xml";
$xml = simplexml_load_file($input);
$data-content = $xml->data->getAssetResponse->content;
$new-data = str_replace("NEW", "OLD", (string)$data-content);
$xml_object->data->getAssetResponse->content = $new-data;
print $xml_object->asXML(); 
?>

我可以知道为什么这不起作用吗?

连字符在 PHP 变量名称中无效。我建议用下划线代替它们,如$new_data$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]*'