【发布时间】:2019-01-25 12:43:54
【问题描述】:
我需要使用 PHP 代码更改 XML 文件中的文本。然后我创建了一个代码:
1- 获取文件
2- 替换文本
3- 用其他名称保存文件。
问题是我在替换 xml 文件中的某些文本时遇到了一些问题。
我可以替换简单的字符串,但不能用“
原始 XML 路径:http://www.csainmobiliaria.com/imagenes/fotos/pisos-NOK.xml
1) 此代码只是将文本 Inmuebles 更改为 xxxxxxxx。 这很好用
$xml_external_path = 'http://www.csainmobiliaria.com/imagenes/fotos/pisos-NOK.xml';
$xml = file_get_contents($xml_external_path);
$response = strtr($xml, array(
'Inmuebles' => 'xxxxxxxx'
));
$newXml = $response;
$newXml = simplexml_load_string( $newXml );
$newXml->asXml('/home/csainmobiliaria/www/pisos-NEW.xml');
2) 现在,如果我使用此代码将文本 <Table Name="Inmuebles"> 更改为 <xxxxxxxx> 我收到 ERROR 500。
$xml_external_path = 'http://www.csainmobiliaria.com/imagenes/fotos/pisos-NOK.xml';
$xml = file_get_contents($xml_external_path);
$response = strtr($xml, array(
'<Table Name="Inmuebles">' => '<xxxxxxxx>'
));
$newXml = $response;
$newXml = simplexml_load_string( $newXml );
$newXml->asXml('/home/csainmobiliaria/www/pisos-NEW.xml');
3) 以同样的方式,如果我使用此代码删除文本 Publicacion 我会收到 ERROR 500。
$xml_external_path = 'http://www.csainmobiliaria.com/imagenes/fotos/pisos-NOK.xml';
$xml = file_get_contents($xml_external_path);
$response = strtr($xml, array(
'<Publicacion>' => ''
));
$newXml = $response;
$newXml = simplexml_load_string( $newXml );
$newXml->asXml('/home/csainmobiliaria/www/pisos-NEW.xml');
这是我需要得到的最终结果:http://www.csainmobiliaria.com/imagenes/fotos/pisos-OK.xml
【问题讨论】:
-
<Table Name="Inmuebles">到<xxxxxxxx>使关闭</Table>无效,关闭<xxx..>不存在。使用解析器并执行此操作。此外,当您get a ERROR 500检查您的错误日志时,它会告诉您出了什么问题。如果它不查看错误报告功能的手册。<Publicacion>方法也有同样的问题。不要对结构化数据(CSV、JSON、XML 等)使用字符串函数,使用适当的解析器。 -
@user3783243 恐怕我不知道什么是“解析器”。你的意思是string int搜索功能吗?
-
simplexml是一个解析器。您应该将文件原样放入其中,根据需要对其进行重组,然后输出。 (如果您不喜欢其他解析器,也可以使用其他解析器) -
XSLT 是一种仅用于此用例的模板语言 - 它将一个 XML 转换为另一个 XML、HTML 或文本。 PHP 有一个扩展 (ext/xsl)。
标签: php xml xslt xml-parsing simplexml