Process XML item with delimited values into PHP array - php

I am trying to process an XML item into a PHP array and simply return it.
However, I am getting "Array to string conversion" as an error on line 3.
PHP Code
function processPlayers($players) { // paramater is the XML item
$playerGUIDS = array();
$playerGUIDArray = explode(";", $players); // CREATE ARRAY FROM STRING WHICH HAVE A ; DELIMINATER
foreach($playerGUIDArray as $player) {
$playerGUIDS[] = $player;
}
return $playerGUIDS;
}
XML Item
<playguid>DC242003;BY523643</playguid>
I am using WP ALL Import as a plugin so I specify my custom field data value as
[processPlayers({playguid[1]})]
See here:
http://www.wpallimport.com/2015/10/wp-all-export-1-1-1-function-editor/
http://www.wpallimport.com/documentation/advanced/execute-php/
My ideal output is below (this is the form of metadata in a WordPress DB).
a:2:{i:0;s:8:"JC745819";i:1;s:8:"JB705789";}

You got error, because WPAllImport try insert this value into database. So, you must return in function string value, not array. In your case, serialized:
function processPlayers($players) {
return serialize(explode(";", $players));
}

I just encountered a closely related case in parsing multiple XML items as an array. As this is one of the highest ranking search results on the topic, I thought the following might help someone else:
WP All Import does not pass an array value to your custom PHP function. If your input element is not a string, but e.g. a list of XML child elements, then WP All Import will pass an empty string if you try to do the following:
<parents>
<parent>...</parent>
<parent>...</parent>
<parent>...</parent>
...
</parents>
[IF(has_special_children({parents[1]}))]
<h2>My Conditional Header</h2>
{parents[1]/parent[8]}
{parents[1]/parent[12]}
{parents[1]/parent[13]}
[ENDIF]
<?php
function has_special_children($parent) {
var_dump(gettype($parent)); // outputs: string
var_dump($parent); // outputs: string ""
return $parent[8] || $parent[12] || $parent[13];
}
?>
In the PHP function, $parent is always an empty string when passing an XML element that has children.
Solution
You can use a variadic function in PHP to pass the elements of interest and check them individually instead:
[IF(wpai_has_any_value({parents[1]/parent[8]}, {parents[1]/parent[12]}, {parents[1]/parent[13]}))]
<h2>My Conditional Header</h2>
{parents[1]/parent[8]}
{parents[1]/parent[12]}
{parents[1]/parent[13]}
[ENDIF]
<?php
function wpai_has_any_value(...$values) {
return (bool) array_filter($values);
}
?>

Related

Get the first element of my array $_POST['tableFields']

I'm trying to get the first element of my asociative array $_POST['tableFields'].
print_r($_POST['tableFields']); // I get: ["id","usuario","apellido1","apellido2","email","password"]
I tryied using reset() method but doesn't show anything.
$campo = reset($_POST['tableFields']);
print_r($campo); // This doesn't show anything.
It is JSON format so its a string value. You must do print_r(json_decode($_POST['tableFields'],1)[0]); or reset(json_decode($_POST['tableFields'],1));

Finding titles in JSON

I currently have this large JSON file: hastebin
But just want the titles of the posts.
I've tried this...
$json = $page;
$o = json_decode($json, true);
echo($json);
$titles = $o["*"]["*"]["*"]["*"]["title"];
var_dump($titles);
But it isn't working - it's returning NULL! Sometimes it just doesn't return anything.
If anyone is wondering, yes this is from Reddit.
This should do it:
$titles = array_map(function($post) {
return $post['data']['title'];
}, $o['data']['children']);
I'm not sure what you expected using "x" indices, but you should probably read about arrays.
PHP can't use wildcards like * in array keys. Whatever string you use to reference the key, it's going to try to find a key with that exact string. So what you tried can't work because there aren't any * keys.
You can get it by iterating all the levels, or iterating the outer level and referring to the proper nested key. But if you're just looking for all instances of 'title' a recursive method may be an easier way to get them.
array_walk_recursive($o, function($value, $key) use (&$titles) {
if ($key == 'title') $result[] = $value;
});
var_dump($titles);
This will get any value of 'title' regardless of its depth in the array, so if that's not what you want, then you'll need to iterate it and specifically reference the proper ones.
It's very hard to deal directly with such a long JSON document. The returned result from the page is not a valid JSON. It contains some HTML tags, but if you take the posts data and insert it in a file you can do the following according to the structure of your JSON (You can find your JSON in an external link here):
<?php
header("Content-Type:application/json");
$posts=file_get_contents('json.php');
//decode your JSON STRING
$posts=json_decode($posts,true);
//create a title variable to store your titles
$titles=array();
foreach($posts['data']['children'] as $child)
{
array_push($titles,$child['data']['title']);
}
echo json_encode($titles);
?>
You can even use this approach using a URL but ensure that it will return a valid JSON with no html

PHP: inline get element from associative array returned by a function

I have a PHP function returning an associative array and I would like to get an element from it. Normally, I first create array from function and then I get element
$associative_array = someFunction();
$element = $associative_array['key'];
Is it possible to get element directly inline? (I can't change function to return the element).
Something like this (which fails due to syntax error, but it's just to show the idea):
$element = someFunction()['key'];

SimpleXML node casting to string not working

I am trying to get a currency rate from this XML file:
http://www.bank.lv/vk/xml.xml
I am getting a currency ID from a HTML form, after that I have to find it according currency rate.
I am using SimpleXML and XPath, my selection is as follow:
$current_rate = $rates->xpath("/CRates/Currencies/Currency[ID='" .$source_currency ."']/Rate");
$source_currency is tested and valid, however, when casting $current_rate to (string), I get the word Array.
Do I have a mistake in the XPath node selection or somewhere else?
$current_rate = $rates->xpath("/CRates/Currencies/Currency[ID='" .$source_currency ."']/Rate");
Will return an array even if just 1 result is returned, if you use print_r you can see what is returned:
print_r($current_rate);
To access it you will have to use:
if (isset($current_rate))
{
echo $current_rate[0];
}
Or if there is the possibility of having more than 1 result for that given $source_currency:
foreach ($current_rate as $rate)
{
echo $rate, "\n";
}

adding data into json with PHP

i used json_decode to create a json object. After going through some elements i would like to add child elements to it. How do i do this?
Depending on which options you passed to json_decode(), you got either an object or array back from it, and you can add elements to these as you would any other object or array.
To add $key => $element to an array:
$myArray[$key] = $element;
Slightly less obvious, but you can add a new public member to an object in PHP as follows:
$myObj->$key = $element;
This will add a member variable from the contents of $key (assuming $key is a string).
If you then pass your array/object into json_encode(), you'll end up with the following json:
{ 'value_of_key' : 'value_of_element' }
I would use json_decode($json,true) with the true flag so that it would come back as an associative array. Then you can add items using the array syntax.

Categories