WP REST API - Strange formatting in response - php

So I'm working with the wp rest api and the wp rest controller plugin. I have a music theme that's doing some interesting things. When i make the API call one of the properties i get is this:
"subheader_img": [
"a:1:{i:0;a:5:{s:5:\"image\";s:0:\"\";s:5:\"color\";s:0:\"\";s:6:\"repeat\";s:6:\"repeat\";s:8:\"position\";s:8:\"left top\";s:11:\"attachement\";s:6:\"scroll\";}}"
],
its a string, that i know should be an array. I'm not sure what type encoding is applied to it. But i'm trying to clean it up on the javascript side. Does anyone know what's being done to this array turned string? And if there are any javascript functions that can help? I've tried JSON.Parse and that obviously won't work because... its not JSON. I've also tried stripping away the first few characters string.substring(x), but i run into the same problem after that.
i know its something simple, i'm just not sure what.
If its possible I'd like to parse it in javascript, modifying the endpoint might be more difficult because of the wordpress theme.

Use WP's functions for serialization:
is_serialized
is_serialized_string
maybe_serialize
maybe_unserialize
The gist: Check if your array item is a serialized string (is_serialized_string), and then maybe_unserialize it. Then you can evaluate the result to see if it's in a format you're expecting (such as an array).

Related

Convert xml to MAP in php using simplexml, NOT json

I'm trying to figure out how to take a simple custom xml file (its actually an EML file, but simpeXML works with it anyway) and take tagnames and the text that follows (i think simpleXML calls them children) and put them into a MAP, with key/value pairs. I've looked at some examples on this site and others about converting to arrays and such but they all seem extremely complicated for my needs. I should note that my custom xml does not contain ANY attributes and this conversion only needs to work with MY custom xml file and not any others ever.
So a simple example of my eml file is here
<lesson>
<unit>4</unit>
</lesson>
So then basically what I would want is a MAP, or whatever a key/value collection is called in php that would give me:
Map[0](lesson,null)
Map[1](unit,4)
It's important that I get the null values (or an empty string is ok too), so I can verify that the eml file is valid. I need to validate it with php, not using a namespace validator or a dtd file or however that is done. So the first key/value pair, or the root tag, HAS to be lesson, and then ill also verify that there is a unit tag, then a title tag, then at least one other type of tag etc...I can do that easy if i can get everything into a key/value collection. Also, there are many tagnames that are the same, so keys should be not-unique. However for the value, they should be unique, but only to the tag name. So unit can only one one "4", but another tag, lets say imageID could also have "4". This is not a requirement but a "nice to have" and I can probably figure that out if its not simple. But if its REALLY hard then I will skip it all together.
I hope this makes sense.
And no, I don't think Im allowed to use json. I'm sure it can be done in simpleXMl but if its impossible, then please provide a method to do it in json (assuming that json is included with PHP and not an extension that has to be loaded).
This is university homework, so I can't use extensions or anything else that would require anything beyond what comes with the XAMPP basic package (php, mysql, apache etc...).
Really surprised I got no votes or views or answers or anything on this. I did figure this out in the end. Oh yeah...got the tumbleweed badge for this too!
Anyway the answer was actually quite simple. I used the simplexml_load_file function in PHP which actually supports any kind of xml-style. So after running this,
$eml = simplexml_load_file("unit.eml");
I then did things like this
foreach ($eml->children() as $child)
$tag = $child->getName();
$tagInfo = $child;
And used $tag and $tagInfo to iterate through my eml and get everything I needed.

How to capture unset REQUEST values in PHP

I'm really unsure if this is even possible but we have an issue where we control an interface that is having XML posted in to it via HTTP post in the form of www.url.com/script.php?xml=<xmlgoeshere>. That is then URL encoded and passed in to us, and we decode and parse it.
Except I have one client who just refuses to url encode their incoming code, which works fine except for when the XML hits an ampersand, at which point everything is being parsed as an end of the xml variable.
www.url.com/script.php?xml=<xmlstart...foo&bar.../>
The end result being that I have XML being POST/GET'd into the xml variable as normal, and then I lose half of the incoming content because of the ampersand.
Now I know that's expected/proper behavior, my question is, is it possible to capture the &bar.../> segment of this code, so that if we hit a known error I can crowbar this into working anyways? I know this is non-ideal but I'm at my wit's end dealing with the outside party.
UPDATE
Ok so I was totally confused. After grabbing the server variables as mentioned below, it looks like I'm not getting the querystring, but that's because on the query they're submitting it has:
[CONTENT_TYPE] => application/x-www-form-urlencoded
[QUERY_STRING] =>
That being the case, is the above behavior still to be expected? Is their a way to get the raw form input in this case? Thanks to the below posters for their help
You'd be hard pressed to do it, if it's even possible, because the fragments of a query string take the format foo=bar with the & character acting as the separator. This means that you'd get an unpredictible $_GET variable created that would take the key name of everything between the & and the next = (assuming there even is one) that would take the value from the = to the next & or the end of the string.
It might be possible to attempt to parse the $_GET array in some way to recover the lost meaning but it would never be all that reliable. You might have more luck trying to parse $_SERVER ['QUERY_STRING'], but that's not guaranteed to succeed either, and would be a hell of a lot of effort for a problem that can be avoided just by the client using the API properly.
And for me, that's the main point. If your client refuses to use your API in the way you tell them to use it, then it's ultimately their problem if it doesn't work, not yours. Of course you should accommodate your clients to a reasonable standard, but that doesn't mean bending over backwards for them just because they refuse to accommodate your needs or technical standards that have been laid down for the good of everyone.
If the only parameter you use is xml=, and it's always at the front, and there are no other parameters, you can do something like this pseudocode:
if (count($_GET)>1 or is_not_well_formed_xml($_GET['xml'])) {
$xml = substr($_SERVER['QUERY_STRING'], 4);
if (is_not_well_formed_xml($xml)) {
really_fail();
}
}
However, you should tell the client to fix their code, especially since it's so easy for them to comply with the standard! You might still get trouble if the xml contains a ? or a #, since php or the web server may get confused about where the query string starts (messing up your $_SERVER['QUERY_STRING'], and either PHP, the client's code or an intermediary proxy or web server may get confused about the #, because that usually is the beginning of a fragment.
E.g., Something like this might be impossible to transmit reliably in a query parameter:
<root><link href="http://example.org/?querystring#fragment"/></root>
So tell them to fix their code. It's almost certainly incredibly easy for them to do so!
UPDATE
There's some confusion about whether this is a GET or POST. If they send a POST with x-www-form-urlencoded body, you can substitute file_get_contents('php://input') for $_SERVER['QUERY_STRING'] in the code above.
YES, Its possible. Using $_SERVER["QUERY_STRING"].
For your url www.url.com/script.php?xml=<xmlstart...foo&bar.../>, $_SERVER["QUERY_STRING"] should contain, xml=<xmlstart...foo&bar.../>;
The following code should extract the xml data.
$pos=strpos($_SERVER["QUERY_STRING"], 'xml');
$xml="";
if($pos!==false){
$xml = substr($_SERVER["QUERY_STRING"], $pos+strlen("xml="));
}
The problem here is that the query string will be parsed for & and = characters. If you know where your = character will be after the "bar" key then you may be able to capture the value of the rest of the string. However if you hit more & you are going to need to know the full content of the incoming message body. If you do then you should be able to get the rest of the content.

Wordpress JSON API Plug-in: How can I put the output of a JSON query into a PHP string?

I installed the JSON API Plug-In for my wordpress site. I want to display on an external site how many posts I have in a certain category.
For example, I have a URL like this: http://mywordpress.com/?json=get_category_posts&slug=press%20releases
Along the output, I almost immediately see a field "post_count" and a number right after it. I want to encapsulate this number into a string so I can output that number onto a table. But in order for me to be able to do that I need to have the entire output in a variable.
But I can't have something like
$json-output = http://mywordpress.com/?json=get_category_posts&slug=press%20releases;
echo $json-output;
That's just gonna output the URL, not the result of the JSON query.
I hope the question is making sense. Any guidance would be appreciated.
You will need to use CURL to get the json result from the URL, then parse the json with PHP, then echo the item you would like displayed.
The parts you seem to be missing are the CURL and JSON parsing, but you are on the right track.
This might help, a pretty simple example:
http://www.katcode.com/http-requests-using-curl-and-decoding-json-responses/

Why need to use JSON in php and AJAX

I just started doing jQuery last week, and so far I already made some basic systems with ajax, like basic jQuery CRUD and simple chat system without referencing on other's work for I decided to test myself on how far I can do systems alone in jQuery(without JSON and XML yet).
But when I decided to look at other's work (hoping to get/learn good practices and codes out there) many or almost every program that deals with ajax have some JSON in it. So I decided to study and read JSON specially this one, but I guess because it's my first time dealing with it, I'm having a problem sinking it into my brain. Yeah I know it is a "lightweight way of describing hierarchical data", I also know how to make JSON like mixing a literal array and object in JS, and how to dsplay it in js.
But my question is, what's the difference and what's the advantage than not using it?
When I can still get and store data on the server using ajax and database without JSON.
By the way I haven't focus on XML yet because based from my research it's better to use JSON in AJAX.
Can you give me some actual scenario dealing with
s1. ajax php mysql (this with what disadvantages?)
and
s2. ajax php mysql json (this with what advantages?)
I mean, my focus is to send and get data, and I already can do it with s1.
Sorry if you find my question stupid. Tia. :)
Why use JSON? The answer is portability and structure.
JSON is portable because parsers and writers are available for many, many languages. This means that JSON that a PHP script generates can be very easily understood by a JavaScript script. It is the best way to transmit complex structures like arrays and objects, and have it still be compatible with multiple languages.
JSON provides structure because the data you transmit with it can have consistent formatting. This is instead of transmitting back plain-text (i.e. unformatted) data, like comma-separated or delimited data.
Data that is merely delimited (for example, "BookName1,BookName2,BookName3") is more difficult for humans to understand, debug, and work with. If you wanted to debug a response between your server and your browser and the data was delimited (like my example above), you might have a hard time understanding it. Also, if you want to add different data types, provide separate records, etc., then your custom data format becomes more complicated. Eventually, you might end up reinventing JSON.
As a side note, JSON is indeed better than XML. It is much more efficient space-wise. There are no tag names to take up space. Structure is created via nested braces, instead of verbose tags.
Resources
Here is an interesting article on the differences and pros/cons of XML and JSON: http://www.json.org/xml.html
Examples
Per your request, here is an example of encoding JSON with PHP. This is ripped from the docs:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
Output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Contrast this to something like this, without JSON:
a,1
b,2
c,3
d,4
e,5
To parse that, you'd have to iterate through each line, split the values yourself, and then create the array. This isn't that difficult, but imagine you have a nested object:
$arr = array ('a'=> array(1,2,3),'b'=> array('a' => 1, 'b' => 2),'c'=>3,'d'=> array(1,2,3,4,5) ,'e'=>5); // etc.
With JSON, it's no different to encode it. Just use json_encode. But, encoding this manually, and then decoding it manually would be significantly more work.
Programming in any sort of programming language, you have several different types of data at your disposal, including the very useful array type.
Interchanging data between Javascript and any server side language can only happen through strings. I.e. you can send and return any text, but there's no way to send a native array or number type.
JSON is an elegant way to express array and other types using only a string. This way you can pass arbitrary data back and forth between different environments and are not limited to pure text. XML solves the same kind of problem, but is often overkill for simple AJAX requests.

Help with using JSON object inside PHP?

I am (trying) to build a web app, first one :)
I need to call a JSON object though, and I am using a simple search form to get a word that I will append to the call, but I need PHP to handle the object when it is returned. How can I do this?
Basically I had the form submit calling a function that, ideally, would go get the object and do what it needs to, then return the results formatted how I want. Does that make sense even?
Thank you!
PHP 5.x has some built in functions: json_decode() and json_encode(). They are worth looking into and should answer your question. If you have less then PHP 5.x the user comments at both of those pages should have alternatives to use in it's place.

Categories