In a custom module of services 3.x Drupal 7 that queries the database, I get the values of the URIs of some images within some nodes.

This is part of module:

$res = db_query("SELECT node.nid AS nid, node.title AS title, body.body_value AS body, fm.uri AS uri 
    FROM {node} node 
    INNER JOIN {field_data_body body} ON body.entity_id = node.nid 
    INNER JOIN {field_data_field_header_image header} ON header.entity_id = node.nid 
    INNER JOIN {file_managed fm} ON fm.fid = header.field_header_image_fid 
    WHERE ((node.status = '1') AND (node.type IN ('tiendas')))
    ORDER BY nid DESC");

    foreach ($res as $cupon) {
    $resultados[] = $cupon;
    }
    return resultados;

And this the json returned by the web services:

[
 {
  "nid": "6",
  "title": "Negron Beach Bar",
  "body": "<p>Este es el descuento de Negron</p>\r\n",
  "uri": "public://negron.png"
 },
 {
  "nid": "5",
  "title": "PizaPuck",
  "body": "<p>Este es el descuento de PizaPuck</p>\r\n",
  "uri": "public://pizapuck.png"
 }
]

But I need the full url. Not the URI. The json should look like this:

 {
  "nid": "5",
  "title": "PizaPuck",
  "body": "<p>Este es el descuento de PizaPuck</p>\r\n",
  "uri": "http://example.com/site/default/files/pizapuck.png"
 }

If I use this from below I get the url I need (in $path), but I have to put the URI value by hand:

    $uri = "public://pizapuck.png"; //by hand
    if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
    $path = $wrapper->getExternalUrl();
    }

How can I do to replace every URI value inside the array? I need to extract every value of URI, modify it and put it back into the array? I understand this is basic and simple, but my knowledge of php, pdo, ppo and mysql are quite poor. Any help on this matter thank you in advance.

Comments

dmpitu’s picture

Finally after trying, searching and searching, this is what worked for me:

I have created a function that replaces the URI with the complete URL.

function uritourl($uri){
  if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
    $path = $wrapper->getExternalUrl();
    return $path;
  }
}

And inside a for I have called it to replace every value in the array.

foreach ($res as $cupon) {
   $resultados[] = $cupon;
  }
for ( $i = 0; $i < count($resultados); $i++){
  $uri = $resultados[$i]->uri;
  $resultados[$i]->uri = uritourl($uri);
}
return $resultados;

There will be more elegant, safe or quick ways to do it, but my knowledge is very scarce. I hope this helps someone.