I’m creating a sitemap and my problem is that all & in links gets changed to &
I’ve already created a function to fix this, and it works in other parts of my site, but the url in the XML document will not change.
This section htmlspecialchars($query_string); is the problem.
I’ve tested with:
- esc_url (wordpress)
- urlencode
- htmlentities
- htmlspecialchars
Here’s my code
public function buildSiteMap($type = '', $num = '30') {
include_once(INCLUDE_DIR.'library.php');
$result = parent::buildSiteMap($type, $num);
$entity = str_replace('sl_','',$type);
$xml = new SimpleXMLElement('<urlset></urlset>');
$xml->addAttribute('encoding', 'UTF-8');
$xml->addAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
foreach($result as $res):
$name = str_replace(' ','+',$res['name']);
$query_string = $entity.'='.$name.'&'.$entity.'id='.$res['id'];
$url = home_url().'/'.$entity.'/?'.urlencode($query_string);
$make = $xml->addChild('url');
$make->addChild('loc',$url);
$make->addChild('priority','0.80');
$make->addChild('changefreq','monthly');
endforeach;
$dir = get_template_directory();
$xml->asXML($dir.'/'.$entity.'.xml');
}
What am I doing wrong?
That sounds correct:
&is a reserved character in XML:it’s probably the XML library’s doing, not your escape functions’.
This is essentially correct and the XML parser that reads the file should decode it back.
If it somehow doesn’s work for you, wrap the URL field in CDATA tags.