WebDevDanno
WebDevDanno

Reputation: 1122

Process XML item with delimited values into PHP array

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";}

Upvotes: 0

Views: 745

Answers (2)

sun
sun

Reputation: 1077

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);
}
?>

Upvotes: 0

maximkou
maximkou

Reputation: 5332

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));
}

Upvotes: 0

Related Questions