John Davidson

PHP not able to add object to JSON

0 comments
Message:


The below code converts the rss feed xml data to json and returns as JSON API.
I need to send the headers of the rss feed too along with result.
So I am trying to add a key called 'headers'


PHPSCRIPT.php?feedURL=http://rss.cnn.com/rss/cnn_topstories.rss


But I get an error Warning: It is not yet possible to assign complex types to attributes in /storage/ssd1/800/19251800/public_html/feed_test.php on line 8


<?php
function Parse($url) {
$fileContents= file_get_contents($url);
;
$fileContents = str_replace(array("\n", "\r", "\t", "&amp;","&nbsp;"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_file($url, "SimpleXMLElement", LIBXML_NOCDATA);
$simpleXml['headers'] = parseHeaders($http_response_header);
return json_encode($simpleXml);
}

function parseHeaders( $headers )
{
$head = array();
foreach( $headers as $k=>$v )
{
$t = explode( ':', $v, 2 );
if( isset( $t[1] ) )
$head[ trim($t[0]) ] = trim( $t[1] );
else
{
$head[] = $v;
if( preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#",$v, $out ) )
$head['reponse_code'] = intval($out[1]);
}
}
return $head;
}

$data = Parse($_GET['feedURL']);
header('Content-Type: application/json; charset=utf-8');
echo $data
?>


My Answer:
To add the headers of the RSS feed along with the JSON result, you can create an associative array in PHP and then encode it to JSON. Here's an example code snippet:

php
$feedURL = $_GET['feedURL'];
$xml = simplexml_load_file($feedURL);
$json = json_encode($xml);

$headers = get_headers($feedURL, 1);

$result = array(
'headers' => $headers,
'feedData' => json_decode($json)
);

echo json_encode($result);
?>


In this code snippet, we first load the RSS feed XML data and encode it to JSON. Then, we use the `get_headers` function to retrieve the headers of the RSS feed URL. We create an associative array `$result` with keys 'headers' and 'feedData', where 'headers' contain the headers of the RSS feed and 'feedData' contains the JSON-encoded RSS feed data.

Finally, we encode the `$result` array to JSON and echo it out as the response. This way, you will get the headers of the RSS feed along with the JSON result.

Rate this post

5 of 5 based on 2619 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us