0

By using the PHP below outputs the values underneath. But because I don't have control of the API output I would like to try and prepend the data with another output such as {"id":0,"name":"Begin","description":"this is my description","url":"http://domain.com"}

Could someone please help?

PHP

<?php
$jsonurl = "/api/styles";
$json = file_get_contents($jsonurl);

echo $json;
?>

OUTPUTS

[{"id":1,"name":"Pale","description":"this is my description","url":"http://domain.com"},{"id":2,"name":"Dawn","description":"this is my description","url":"http://domain.com"}]
3
  • This is json, not a PHP array. Is it supposed to be converted into a PHP array, or do you just want to prepend your own json to the json from the API? Commented Jan 26, 2014 at 15:37
  • @jd182 I'd like to add that json to the front of the printed Commented Jan 26, 2014 at 15:38
  • As I understand, you want to prepend your data in order to "sanitize" to some extent the output of the API you can't control, right? Commented Jan 26, 2014 at 15:40

4 Answers 4

1

Is this what you have in mind?

<?php
$jsonurl = "/api/styles";
$json = file_get_contents($jsonurl);
$json = '[{"id":0,"name":"Begin","description":"this is my description","url":"http://domain.com"},' . substr($json, 1);
echo $json;
?>

Output:

[{"id":0,"name":"Begin","description":"this is my description","url":"http://domain.com"},{"id":1,"name":"Pale","description":"this is my description","url":"http://domain.com"},{"id":2,"name":"Dawn","description":"this is my description","url":"http://domain.com"}]
Sign up to request clarification or add additional context in comments.

1 Comment

The OPs title is misleading. This is simple string concatenation.
1
$jsonurl = "/api/styles";
$json = file_get_contents($jsonurl);
$begin = '{"id":0,"name":"Begin","description":"this is my description","url":"http://domain.com"}';

$data = json_decode($json);
array_unshift($data, json_decode($begin));

echo json_encode($data);

Comments

0

If it really is json, parse it (decode_json()) and print it anyway you like.

Comments

0

I'm not exactly certain what you're wanting to "prepend" but you can turn it into a PHP array, reverse it then push new elements onto the array.

$json = file_get_contents($jsonurl);
$array = json_decode($json, true);
$reversed = array_reverse( $array );
$reversed[] = ['id' => 0, 'name' => 'Something];

Reverse it back and encode it.

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.