I have some JSON that looks like this:
{
people: []
}
My Goal at the moment is to simply add elements to the array of people. But in the end I also would like to be able to remove the elements again.
I have tried something like:
<?
$file = "test.json";
$json = file_get_contents($file);
$get = json_decode($json);
array_push($get->people, $_GET['person']);
file_put_contents($file, json_encode($get));
?>
However, this does not work. I'm pretty sure there is an easier solution for this. Thanks for any help.
You have invalid JSON. Keys must be quoted.
{"people": []}
Otherwise, your code should work. Although I would recommend not using PHP short open tags and filtering user input.
Related
I'm working with an API that returns JSON and I'm using PHP to display it. Inside the JSON is HTML tags. I've been reading about the many ways you can remove them from the returned JSON but I have so many unique tags that I'm wondering what the easiest method would be? A lot of other questions seem to focus on specific tags and finding a solution to remove them. Is it possible to just remove all known HTML tags or do I need to program each one individually? If the answer is yes, what is the method for doing so?
Thank you for your time and input.
Simply do this:
$data = json_decode($your_json_string, TRUE);
array_walk_recursive($data, function(&$v) { $v = htmlentities($v); });
or to remove tags completely
array_walk_recursive($data, function(&$v) { $v = strip_tags($v); });
I have a php file that has an array in it. I'd like to be able to add an item to that array using a simple form.
Here is an example similar to my array:
$list = array("BA0UKSF","BA9IHHE","BAC8GMB","BAC8HMC","BAC8HMC","BAC8HMC","BACI60T","BAEIDFD","BAEIEFE","BAEIEFE","BAMB0","BAOUKSE","BAOUKSF","BAPQADL","BAPQADM","BUNDLE","CN3ICDC","CN3ICDCA","CN7IZDPA","CN8ID42","CN8ID72","CNECBCBA");
I'd like to add the new item to the array someplace either at the beginning or end of the array list.
I know how to pass the forms data to php but what I dont know is how to get php to open this file, locate the array and add something to it.
I'd just store your array data in JSON format what makes it very easy to operate on the array.
Reading array:
$list = json_decode(file_get_contents($file));
Saving array:
file_put_contents($file, json_encode($list));
Reasons:
It is very bad practice to patch PHP code. (difficult to maintain; will possibly stop to work as you change the code in the file etc.)
If your input you add to $list is user-input and not 100% validated, it may be malicious code in it...
You can parse the text file line by line and locate the array first. And then, you can simply use:
array_push() -- if you want to add elements to the end of the array
array_unshift() - if you want to add elements to the beginning of the array
Examples:
array_push($list, "CN7IZDPA"); //adding to the end
array_unshift($list, "CN7IZDPA"); //adding to the beginning
But reading your array definition from a text file seems like a bad idea. You really should use a database as it makes managing the stuff easier.
Hope this helps!
So I found some answers on how to do this, but none of them actually worked, i.e. json_decode(). This is what I did:
I created js object/array
Then I passed it to php file via Ext.Ajax.Request as JSON.stringify(js object)
Now in my php I see the result of that string as follows: ["James;","George;"]
I want to get it as an php array like (James, George). Any easy way to do this or I have to remove unnecessary parts manually?
OK, I was looking at this problem for a while and finally got the answer.
Inside php, I needed to add json_decode(stripslashes($scenarios)), where $scenarios = ["James;","George;"].
Code: ($scenarios is sent from js file via Ajax using JSON.stringify(js object))
<?php
$scenarios = empty($_GET['scenarios']) ? false : $_GET['scenarios'];
// more code for validation
$arr = json_decode(stripslashes($scenarios));
?>
Now $arr will become regular php array.
Use html_entity_decode function
I have an HTML file that I have downloaded using curl and inserted into a string. The HTML file has a lot of content but I am looking to parse a certain section of the document and insert this section into an array. The tricky part of this is that the section that I'm trying to parse is NOT HTML, it's code in JavaScript block:
<!-- script block -->
<script type="text/javascript" src="//external.site.com/76b07.js"></script>
<script>....code.....
"235533":{"itemId":"235533","type":"0","image":{"url":"thispic.jpg"}:"summary":"This Item"},
"235534":{"itemId":"235534","type":"1","image":{"url":"thisotherpic.jpg"}:"summary":"This Other Item"},
</script>
How can I import item information as an array?:
$array = array( "itemId" => "235533", "type" => "0", "image" => "thispic.jpg", "summary" =>"This Item" );
You might use a RegExp to match "....":{....} located between <script> tags. The strings, you're interested in, are JSON variables.
Once you have each json variable in a string, you could try with json_decode()
$json_string = '"235533":{"itemId":"235533","type":"0","image":{"url":"thispic.jpg"}:"summary":"This Item"}';
$json = json_decode($json_string);
$myArray = (array)$json;
Try json_decode function in php
You would first need to figure out how to isolate the data structure using whatever string searching methodologies you can use that are repeatable even when the data changes. It is hard to say what this might be without further context from you about the content around the data structure - i.e. what is the same in all cases, and what varies.
You would then eventually get the data strings and json_decode them as others have suggested.
use regex to match them
preg_match_all('/[0-9]+":{"itemId":"(?P<itemId>[0-9]*)","type":"(?P<type>[0-9]{1})","image":{"url":"(?P<image>.*)"}:"summary":"(?P<summary>.*)}/',$mystring,$elements,PREG_SET_ORDER);
then loop through $elements to get your values
Use explode. For example, something like
$array = explode('","', $string);
that would get close to what you want.
Edit:
This looks like a better fit for you.
I am running a Debian box with PHP v5.2.17. I am trying to get around the cross-domain issue with an XML file and am using this got to fetch any xml and return json:
<?php
header('content-type: application/json; charset=utf-8');
if( strlen($_GET["feed"]) >= 13 ) {
$xml = file_get_contents(urldecode($_GET["feed"]));
if($xml) {
$data = #simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($data);
echo isset($_GET["callback"]) ? "{$_GET[’callback’]}($json)" : $json;
}
}
?>
The problem is, its not returning valid json to jquery.. The start character is "(" and the end is ")" where jquery wants "[" as the start and "]" as the end. I've taken the output and used several online validation tools to check it..
Is there a way I can change these characters prior to sending back or pass json_encode options?
You could change json_encode($data) to json_encode(array($data)) if it expects an array (like you're saying):
$json = json_encode(array($data));
EDIT: Also, I believe the SimpleXml call will result in a bunch of SimpleXmlElements, perhaps json_encode then thinks it should be objects, instead of arrays? Perhaps casting to an array will yield the correct results.
You cannot json_encode() SimpleXMLElements (that's the type that is returned by simplexml_load_string(). You have to convert the data from the XML file into some native PHP type (most likely an array).
SORRY that's wrong. json_encode() can in fact encode SimpleXMLElements (at least on my PHP version 5.3.4). So if your client-side code expects an array you must wrap your $data in an array:
$json = json_encode(array($data));
We can use json_encode() function most probably on array. so you first take XML content into PHP array and then apply json_encode().I think this will solve your problem..
It seems that you are sending an empty callback parameter or something, but the callback parameter in jQuery must look exactly like this: callback=?