boop
boop

Reputation: 7788

How to send UTF8 to the WordPress REST-API?

Malformed UTF-8 characters, possibly incorrectly encoded

Disclaimer: Character encodings confuse me a lot.
I want to create a lot of posts automated via the WordPress REST-API. I can create posts without an issue - unless I got special characters in my content. Emojis for example.

$params = @{
    title = $Title
    content = $Content # "foobar" would work just fine; 
                       # "👎äöü" will give me an error
}

Invoke-RestMethod -Uri "https://my.blog.foo/wp-json/v2/posts" `
                  -Method POST `
                  -Headers @{ Authorization = ("Basic {0}" -f $ACCESS_TOKEN) } ` 
                  -ContentType "application/json" `
                  -UseBasicParsing `
                  -Body $($params | ConvertTo-Json) 

I assume this actually isn't a WordPress related issue. Anyhow I'm fiddling aroundd for quite a while now and I just can't figure out a way to send my content without malforming ("ö" gets "?") it.

Upvotes: 0

Views: 3477

Answers (2)

Sage Pourpre
Sage Pourpre

Reputation: 10323

Use -ContentType "application/json; charset=utf-8"; instead.

If it doesn't work, You might also need to encode your body to UTF8 too. $body = [System.Text.Encoding]::UTF8.GetBytes($body);

Complete example

$params = @{
    title = $Title
    content = $Content # "foobar" would work just fine; 
                       # "👎äöü" will give me an error
}

$Body = $params | ConvertTo-Json
$Body = [System.Text.Encoding]::UTF8.GetBytes($body)

$Splat_Post= @{
    ContentType = "application/json; charset=utf-8"
    UseBasicParsing = $true
    Method = 'POST'
    Uri = "https://my.blog.foo/wp-json/v2/posts"
    Headers = @{ Authorization = ("Basic {0}" -f $ACCESS_TOKEN) }
}

Invoke-RestMethod @Splat_Post-Body $Body

Note: I reworked the code to demonstrate splatting .

Should you need to call that method with all the same parameters each time except body, you could call it like that : Invoke-RestMethod @Splat_Post -Body $Body then just changing the $Body to the content of your desires each time.

Upvotes: 1

halv
halv

Reputation: 121

You could try and encode the body as UTF8 before posting it

-Body ([System.Text.Encoding]::UTF8.GetBytes(($params | ConvertTo-Json)))

Upvotes: 0

Related Questions