0

I have the following php code. I am able to get the value stored in my variable and printed. But after json_encode, the value became 'empty'. Is there a bug in json_encode ? I am using Php 7.2 on ubuntu 18

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://www.thestar.com.my/rss/news/nation');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($ch);
curl_close($ch);

$rss = simplexml_load_string($xml);
$cnt = count($rss->channel->item);
$items = array();
$items[0]['title'] = $rss->channel->item[0]->title;
$items[0]['url'] = $rss->channel->item[0]->link;
echo $items[0]['title'] . PHP_EOL;
echo $items[0]['url'] . PHP_EOL;
echo json_encode($items) . PHP_EOL;
?>

See the output below. What is wrong with the json_encode ? Why after the json_encode, the title became empty ?

Sabah updates SOPs for places of worship and childcare centres
https://www.thestar.com.my/news/nation/2021/06/13/sabah-updates-sops-for-places-of-worship-and-childcare-centres
[{"title":{"0":{}},"url":{"0":"https:\/\/www.thestar.com.my\/news\/nation\/2021\/06\/13\/sabah-updates-sops-for-places-of-worship-and-childcare-centres"}}]

2 Answers 2

2

json_encode produces an empty object tag ({}) when passed PHP objects that do not implement JsonSerializable or contain public member variables.

You pass it \SimpleXMLElement nodes, not strings.

In your echo it just shows because the XML entities implement __toString() which echo invokes.

Either do that aswell or cast it to (string):

<?php
$rss = simplexml_load_string($xml);
$items = array();
$items[0]['title'] = $rss->channel->item[0]->title->__toString();
$items[0]['url'] = (string) $rss->channel->item[0]->link;
echo json_encode($items) . PHP_EOL;
?>
Sign up to request clarification or add additional context in comments.

5 Comments

Got it !! Thanks. Appreciated very much
Found out another method too. $items[0]['title'] = utf8_encode($rss->channel->item[0]->title); Thank you.
It would also work with trim, many methods force string conversion of the input. utf8_encode however is not something you should just put around everything. If the input was already UTF8 encoded then you destroy special characters with it by double-encoding.
utf8_encode() is a misnamed function that converts from ISO-8859-1. If you aren't using ISO-8859-1 it'll just corrupt your data.
@Jsmidt If your question is solved by that I'd appreciate marking the answer as accepted :)
0

Thanks..Got it with

$items[0]['title'] = $rss->channel->item[0]->title->__toString();

Comments

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.