如何更换特殊符号?

时间:2013-02-01 01:14:06

标签: php xml-parsing

  

可能重复:
  Parsing xml from url php

我需要从url解析xml-document并解决使用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>

3 个答案:

答案 0 :(得分:1)

你知道

str_replace不会对某个对象起作用。但是,如果您将此输出为html,则可以保留实体。

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

您将无法使用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