1

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

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

4

1 回答 1

0

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

于 2012-05-04T02:00:30.367 回答