php:xml解析并返回xml

时间:2012-05-03 22:24:12

标签: php xml xml-parsing simplexml

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(); 
?>

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

1 个答案:

答案 0 :(得分:0)

连字符在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>

From the PHP documentation:

  

变量名遵循与PHP中其他标签相同的规则。有效的变量名称以字母或下划线开头,后跟任意数量的字母,数字或下划线。作为正则表达式,它将表达为:'[a-zA-Z_ \ x7f- \ xff] [a-zA-Z0-9_ \ x7f- \ xff] *'