I am trying to get data from database and write it to xml file using DOM.
$doc = new DomDocument('1.0', 'UTF-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$root = $doc->createElement('root');
$doc->appendChild($root);
$blocks = $doc->createElement('blocks');
$root->appendChild($blocks);
while($result_array = mysqli_fetch_assoc($result))
{
$cms_block = $doc->createElement('cms_block');
foreach($result_array as $fieldname => $fieldvalue)
{
/*This is part that is not working*/
$key = $doc->createElement($fieldname);
$cms_block->appendChild($key);
$value = $doc->createTextNode($fieldvalue);
$key->appendChild($value);
}
$stores = $doc->createElement('stores');
$cms_block->appendChild($stores);
$item = $doc->createElement('item');
$stores->appendChild($item);
$itemvalue = $doc->createTextNode('0');
$item->appendChild($itemvalue);
$blocks->appendChild($cms_block);
}
The above code works and mostly does what I need it to do but it fails within foreach loop and the elements and value that I am trying to add within foreach does not work.
Example of $result_array = mysqli_fetch_assoc($result)
Array ( [title] => Footer Links [identifier] => footer_links [is_active] => 1 )
Array ( [title] => Footer Links [identifier] => footer_links [is_active] => 1 )
It would really help me if someone can tell me what I am doing wrong within foreach loop which is not adding the data that I am getting from database to the xml file please.
Try this to add data from your $results_array
$cms_block->appendChild($doc->createElement($fieldname, $fieldvalue));
UPDATE
Move $blocks->appendChild($cms_block); to the end of your while loop .
Related
I am building a simple api to Post/Return XML for my app. Here is the code:
$returnData = array (
"ResultCode" => "0",
"ResultString" => "uppdated"
);
$xml = new DOMDocument();
$dateInfoElement = $xml->createElement("versionCheckResult");
foreach ($returnData as $key => $value) {
$xmlNode = $xml->createElement($key,$value);
$dateInfoElement->appendChild($xmlNode);
}
$xml->appendChild($dateInfoElement);
echo $xml;
Sadly, I am getting no return, not a thing. Php is not my strong side but it seemed easier than working with Node.JS and mongoDB. Can you tell me what I am doing wrong?
If you're using DOMDocument, you need to use this method to display your XML as a string : DOMDocument::saveXML()
$returnData = array (
"ResultCode" => "0",
"ResultString" => "uppdated"
);
$xml = new DOMDocument();
$dateInfoElement = $xml->createElement("versionCheckResult");
foreach ($returnData as $key => $value) {
$xmlNode = $xml->createElement($key,$value);
$dateInfoElement->appendChild($xmlNode);
}
$xml->appendChild($dateInfoElement);
echo $xml->saveXML(); //This should works as expected
I am having trouble with my php code below. I am trying to have the function below to return the UPC and imageURL for each item. When I print_r the result after the loop I receive this.
Array
(
[upc] => 043396066731
[ImageURL] => http://ecx.images-amazon.com/images/I/51HKXNNT53L._SL200_.jpg
)
Array
(
[upc] => 096009394097
[ImageURL] => http://ecx.images-amazon.com/images/I/512NKNWC8EL._SL200_.jpg
)
However, when I use return result and then print_r I only receive the last response. Why is this and how can I fix my code to receive the values from both items? I have searched Google and other Stackoverflow questions and can find similar situations, but I am still struggling.
Array
(
[upc] => 096009394097
[ImageURL] => http://ecx.images-amazon.com/images/I/512NKNWC8EL._SL200_.jpg
)
Here is my function
function invokeGetMatchingProductForId(MarketplaceWebServiceProducts_Interface $service, $request)
{
// try {
$response = $service->getMatchingProductForId($request);
$dom = new DOMDocument();
$dom->loadXML($response->toXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$parsed_xml = simplexml_import_dom($dom);
//print_r($parsed_xml);
$Result = array();
foreach($parsed_xml->GetMatchingProductForIdResult as $item )
{
$status = $item->attributes()->status;
if (stristr($status, "Success") == true)
{
$Result['upc'] = (string)$item->attributes()->Id;
$Result['ImageURL'] = str_replace('SL75','SL200',$item->Products->Product->AttributeSets->children('ns2', true)->ItemAttributes->SmallImage->URL);
} else {
$Result['upc'] = (string)$item->attributes()->Id;
$Result['ImageURL'] = "";
}
}
print_r($Result);
}
// return $Result;
// }
// $amazonResult =invokeGetMatchingProductForId($service, $request);
// print_r($amazonResult);
You need to assign second key for your array:
$Result['upc'][] = ;
$Result['ImageURL'][] = ;
^-----
Currently you are resetting this $Result['upc'] every time you assign new value.
according to your requirement you need to create two dimensional array
use foreach like this
foreach($parsed_xml->GetMatchingProductForIdResult as $item )
{
$status = $item->attributes()->status;
if (stristr($status, "Success") == true)
{
$Result[]['upc'] = (string)$item->attributes()->Id;
$Result[]['ImageURL'] = str_replace('SL75','SL200',$item->Products->Product->AttributeSets->children('ns2', true)->ItemAttributes->SmallImage->URL);
}
else
{
$Result[]['upc'] = (string)$item->attributes()->Id;
$Result[]['ImageURL'] = "";
}
}
print_r($Result);
The code below scrapes two values from a webpage and adds them to an array. I've got as far as being able to print the first row of that array but I'm unable to get the whole thing.
I presume some sort of loop will be required but my attempts so far have been unsuccessful.
I feel this should be fairly basic. Any idea what I can do to achieve the desired result?
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query("$product_location");
if ($row->length > 0) {
foreach ($row as $location) {
$products['product_url'] = $product_url_root.$location->getAttribute('href');
$products['shop_name'] = $shop_name;
$row = $xpath->query($photo_location);
/* FIND LINK TO IMAGE */
if ($row->length > 0) {
foreach ($row as $location) {
$products['photo_url'] = $photo_url_root.$location->getAttribute('src');
}
}
}
print_r($products);
}
}
EDIT
I should say that I'm hoping to get the array in this format:
Array (
[0] {product_url => 123, shop_name => name, photo_url => abc},
[1] {product_url => 456, shop_name => name, photo_url => def},
[2] {product_url => 789, shop_name => name, photo_url => ghi},
)
The plan is eventually to be able to use the following code in the place of print_r($products) to create an XML file:
$item = $channel->addChild("item");
$item->addChild("product_url", $entry['product_url']);
$item->addChild("shop_name", $entry['shop_name']);
$item->addChild("photo_url", $entry['photo_url']);
You'll need the following details to create the associative array you need:
the product URL
the shop name
the product image URL
Now, in your code, you're looping through the product URLs — and for each product URL, you're looping through the list of product image URLs. This will cause the code inside the nested foreach to be executed n^2 times. You do not want that.
Here's how you should structure your loops:
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i]
);
}
print_r($result);
I have this link http://lazhalazha.livejournal.com/data/rss with RSS in it, what I need to get is array of guid values, that is links to the post. This is what I have so far...
$xml = simplexml_load_file('http://lazhalazha.livejournal.com/data/rss');
foreach ($xml->channel->item as $item){
print_r($item->guid);
}
Output is series of these objects
SimpleXMLElement Object
(
[#attributes] => Array
(
[isPermaLink] => true
)
[0] => http://lazhalazha.livejournal.com/713.html
)
Solved this by converting this object to string, then it's passing correct URL instead of object.
$xml = simplexml_load_file('http://lazhalazha.livejournal.com/data/rss');
$linkArray = array();
foreach ($xml->channel->item as $item){
$guid = (string)$item->guid;
array_push($linkArray, $guid);
}
<?php
$_temp = array();
$xml = simplexml_load_file('http://lazhalazha.livejournal.com/data/rss');
foreach ($xml->channel->item as $item){
$_temp[] = (string)$item->guid[0];
}
print_r($_temp);
?>
Been trying to figure this out for a short while now but having now luck, for example I have an external xml document like this:
<?xml version="1.0" ?>
<template>
<name>My Template Name</name>
<author>John Doe</author>
<positions>
<position>top-a</position>
<position>top-b</position>
<position>sidebar-a</position>
<position>footer-a</position>
</positions>
</template>
How can I process this document to create variables like this:
$top-a = top-a;
$top-b = top-b;
$sidebar-a = sidebar-a;
$footer-a = footer-a
If you can't make them into variables, how would you put them into an array?
Any help will be greatly appreciated.
From the PHP web site at http://www.php.net/manual/en/function.xml-parse.php:
Ashok dot 893 at gmail dot com 26-Apr-2010 05:52
This is very simple way to convert all applicable objects into associative array. This works with not only SimpleXML but any kind of object. The input can be either array or object. This function also takes an options parameter as array of indices to be excluded in the return array. And keep in mind, this returns only the array of non-static and accessible variables of the object since using the function get_object_vars().
<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
$arrData = array();
// if input is object, convert into array
if (is_object($arrObjData)) {
$arrObjData = get_object_vars($arrObjData);
}
if (is_array($arrObjData)) {
foreach ($arrObjData as $index => $value) {
if (is_object($value) || is_array($value)) {
$value = objectsIntoArray($value, $arrSkipIndices); // recursive call
}
if (in_array($index, $arrSkipIndices)) {
continue;
}
$arrData[$index] = $value;
}
}
return $arrData;
}
?>
Usage:
<?php
$xmlUrl = "feed.xml"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
print_r($arrXml);
?>
This will give the following result:
Array
(
[name] => My Template Name
[author] => John Doe
[positions] => Array
(
[position] => Array
(
[0] => top-a
[1] => top-b
[2] => sidebar-a
[3] => footer-a
)
)
)
You want the built in class Simplexml
Take a look at SimpleXML:
http://www.php.net/manual/en/simplexml.examples-basic.php
It parses XML into a "map-like" structure which you could then use to access your content. For your particular case,
$xml = new SimpleXMLElement($xmlstr);
$top_a = $xml->template->positions[0]
The simplest method is to use SimpleXML:
$xml = simplexml_load_string(... your xml here...);
$values = array()
foreach($xml->positions as $pos) {
$values[$pos] = $pos;
}
You do not want to auto-create variables in the manner you suggest - it litters your variable name space with garbage. Consider what happens if someone sends over an XML snippet which has <position>_SERVER</position> and you create a variable of that name - there goes your $_SERVER superglobal.
why not doing the array directly?
var positions = document.getElementsByTagName("positions");
var positions_final_arr = [];
for(int i = 0; i < positions.length; i++){
positions_final_arr[i] = [];
var inner_pos = positions[i].getElementsbyTagName("position");
for(int l = 0; l < inner_pos.length; l++){
positions_final_arr[i][l] = inner_pos[i].value;
}
}
console.log(positions_final_arr);
$str = "your xml";
$xml = simplexml_load_string($str);
$result = array();
foreach ($xml->positions as $pos) {
foreach ($pos->position as $p) {
$element = (string)$p[0];
$result[$element] = $element;
}
}
var_dump($result);
Use SimpleXML to parse the file into an object/array structure, then simply use list:
$sxml = new SimpleXMLElement($xml);
$positions = (array)$sxml->positions->children();
list($top_a, $top_b, $sidebar_a, $footer_a) = $positions['position'];
$dom = new DOMDocument;
$dom->loadXML('<root><position>a</position></root>'); //your string here
//$dom->loadXML(file_get_contents($file_with_pxml)); - from file
$position = $dom->getElementsByTagName('position');
for ($i=0; $i<$position->length; $i++)
{
$item = $position->item($i);
${$item->nodeValue} = $item->nodeValue;//$$item->nodeValue = $item->nodeValue;
}
But as I know - you can't create variable with dash in name in PHP
<?php
$xmlUrl = "feed.xml"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = json_decode(json_encode($xmlObj), true); # the magic!!!
print_r($arrXml);
?>
This will give the following result:
Array
(
[name] => My Template Name
[author] => John Doe
[positions] => Array
(
[position] => Array
(
[0] => top-a
[1] => top-b
[2] => sidebar-a
[3] => footer-a
)
)
)