0

I need to convert the & in a string to & in php. I have a function to pull in some custom data in to an RSS feed. In this case it is a url which could look something like http://google.com?something=here&somethingelse=here&somethingelse=there

The problem is the amperstand shows in the feed and is not converted to & so when I try using simplepie to fetch the feed it throws an error This XML document is invalid, likely due to invalid characters. XML error: not well-formed (invalid token)

This is the function I have to add the custom data to the feed:

/** Add ACF fields to RSS **/
add_action('rss2_item', 'cupusa_rss2_item');
function cupusa_rss2_item() {
    global $post;

    $memberEvent_link = get_field('member_event_link', $post->ID);

    $output = '';
    if( $post->post_type == 'jobs' ) {
        $job_link_url = get_field('job_link', $post->ID);

            $output .= "<job_link>{$job_link_url}</job_link>";

    }

    if($memberEvent_link){
        $output .= "<member_event_link>{$memberEvent_link}</member_event_link>";
    }

    echo $output;
}

When using simplepie it is pulling this http://google.com?something=here&somethingelse=here&somethingelse=there when it should be proper xml like this http://google.com?something=here&#038;somethingelse=here&#038;somethingelse=there

So my question is how do I modify my function above to convert the & to &#038; for the $job_link_url variable? Sometimes the link may have the & and sometimes it may not.

1 Answer 1

2

The htmlspecialchars function will convert all characters which have special meaning in XML.

$job_link_url = get_field('job_link', $post->ID);
$xml_safe_job_link_url = htmlspecialchars($job_link_url, ENT_XML1 | ENT_QUOTES);
Sign up to request clarification or add additional context in comments.

1 Comment

In addition, if you want to use & in an URL, PHP offers you urlencode().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.