如何替换特殊符号


How to replace special symbol?

可能的重复项:
从网址 php 解析 xml

我需要从 url 解析 xml 文档并解决使用 CURL,因为我的托管无法使用某些 dom 或 simplexml 函数。我如何替换欧元符号并展示它们。功能str_replace对我没有帮助。

<?php
$url = 'http://www.aviasales.ru/latest-offers.xml';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'app');
$query = curl_exec($ch);
curl_close($ch);
$xml=simplexml_load_string($query);
//$xml = str_replace('&euro;', '€', $xml);
?>
<table width=100%>
    <tr bgcolor="#CAE8F0" align="left">
        <td><b><?= $xml->offer[1]['title']?></b></td>
       <td width=5%><b><a href="<?=$xml->offer[1]["href"]?>">buy</a></td>
    </tr>
</table>
str_replace你发现的对

对象不起作用。但是,如果要将其输出为 html,则可以将实体保留原样。

如果需要对其进行解码,请通过 html_entity_decode 运行属性,而不是整个对象。

在你的

代码中,$xml不是一个字符串,而是一个SimpleXMLElement。在加载字符串之前,您可能可以替换 € 实体:

$xml = simplesml_load_string(str_replace('&euro;', '€', $query));

只要$query是用多字节字符编码的,你应该没问题。如果没有,您可能不得不遍历$xml。

您将无法使用 SimpleXML 直接编辑 XML:

SimpleXML 扩展提供了一个非常简单且易于使用的工具集,用于将 XML 转换为可以使用普通属性选择器和数组迭代器处理的对象。http://www.php.net/manual/en/intro.simplexml.php

你必须使用 PHP DOM 扩展:

DOM 扩展允许您通过 PHP 5 的 DOM API 对 XML 文档进行操作。http://www.php.net/manual/en/intro.dom.php

例:

// Create
$doc = new DOMDocument();
$doc->formatOutput = true;
// Load
if(is_file($filePath))
    $doc->load($filePath);
else
    $doc->loadXML('<rss version="2.0"><channel><title></title><description></description><link></link></channel></rss>');
// Update nodes content
$doc->getElementsByTagName("title")->item(0)->nodeValue = 'Foo';
$doc->getElementsByTagName("description")->item(0)->nodeValue = 'Bar';
$doc->getElementsByTagName("link")->item(0)->nodeValue = 'Baz';

结合问题和所选答案的示例:https://stackoverflow.com/a/6001937/358906