php - reading data from xml and create an array object - php

I am new to php, I am using metro-websign for creating my website. There is a plugin taking an array. The following code works fine:
<? php
$photoNewsPath = array(
"photo/committees/spirit-rock/20150203-anna.jpg",
"photo/news/20150207 - 100 day.jpg"
);
$photoNewsTitle = array("Post your photos on the website", "100 school day = pajama day fun");
var_dump($photoNewsPath);
$tile[] = array(
"type" => "slideshow",
"images" => $photoNewsPath,
"classes" => "");
But when I read the array from an xml file:
<? php
$photonews = simplexml_load_file("config\photonews.xml") or die("Error: Cannot create object");
foreach($photonews - > news as $news) {
$photoNewsPath[] = (string) $news - > path;
}
var_dump($photoNewsPath);
$tile[] = array(
"type" => "slideshow",
"images" => $photoNewsPath,
"classes" => ""); ?>
the plugin doesn't work anymore. I use var_dump to dump the array from both code snippets. The results are identical. What could make the arrays different so the php plugin fails?
Any clues?

you have an error into foreach. this is the correct code to access at the
<path></path> tag into xml
<?php
$photonews = simplexml_load_file("config/photonews.xml") or die("Error: Cannot create object");
$photoNewsPath=array();
foreach($photonews as $key => $value) {
$photoNewsPath[]= (string) $photonews->path;
}
// var_dump($photoNewsPath);
$tile[] = array(
"type" => "slideshow",
"images" => $photoNewsPath,
"classes" => ""); ?>

Related

What's the right way of getting category list of a Wordpress web site using PHP?

I need to read the list of Wordpress categories of a blog and insert them as hyperlinks into my PHP Page.
I used simplexml_load_file and it's working on my local Wamp Server perfectly.
But I'm worried about performance of the production server with a lot of users. Should I do caching for production page? How? Is there another standard solution for this?
$feed_url = "http://my.web.site/category/$category/feed/";
// If there is some errors, return empty
if(! $news_xml = #simplexml_load_file($feed_url, 'SimpleXMLElement', LIBXML_NOCDATA & LIBXML_NOWARNING & LIBXML_NOERROR))
{
log_message('error','Feed load error: '.$feed_url);
return [];
}
$data = [];
foreach ($news_xml->channel->item as $news_item) {
$new_item = [
"title" => (string)$news_item->title,
"link" => (string)$news_item->link,
"comments" => (string)$news_item->comments,
"pubDate" => (string)$news_item->pubDate,
"category" => (string)$news_item->category,
"guid" => (string)$news_item->guid,
"description" => (string)$news_item->description,
];
if ($news_item->children('media', true)->content) {
$new_item["image_url"] = (string)$news_item->children('media', true)->content->attributes()->url;
}
$data[] = $new_item;
}

How do I put a SimplePie Enclosure Link into an Array

I am attempting to parse an RSS feed which uses media enclosures. I am using SimplePie and I have been able to parse it, and make all the needed elements appear on the page.
But I am writing a plugin for a CMS and I need to put those elements into an array. All are working fine, except the $item->get_enclosure().
I should say, that in the array, what is returned is a string of gibberish. I need it to return the url to the file.
Here is the relevant code:
// Get Enclosure
$enclosures = array();
$item_enclosures = $item->get_enclosures();
if ( ! empty($item_enclosures))
{
foreach ($item_enclosures as $enclosure)
{
if ($enclosure = $item->get_enclosure())
{
$enclosure->get_link();
} else {
$enclosure->get_title();
}
}
}
$items[] = array(
'item_title' => $item->get_title(),
'item_link' => $item->get_permalink(),
'item_date' => $item->get_date('U'),
'item_content' => $item->get_content(),
'item_img' => $item->get_enclosure(),
'item_description' => $item->get_description(),
'item_categories' => $categories,
'item_authors' => $authors
);
}
return $items;
Does anyone know how to make the 'item_img' return a link to the file, rather than what seems to be some kind of encoded string of characters.
From http://simplepie.org/wiki/reference/simplepie_enclosure/get_link
$link = $item->get_enclosure()->get_link();
would seem to do what you want.

How could I reorganize json arrays and give key string to each key while arraying them into arrays within an array through php?

currently I use three separate php functions to array:
folder names
a thumbnail under the folder
a text file under the folder
into three separated json files, so they now are:
["folder1","folder2","folder3"]
["folder1/thumb.svg","folder2/thumb.svg","folder3/thumb.svg"]
["blah blah blah","blah blah blah","blah blah blah"]
This works fine for me but it would be so much easier if I can make them into one json file looks like this:
[
{
"name" : "folder1",
"thumbnail" : "folder1/thumb.svg",
"text": "blah blah blah"
},
{
"name" : "folder2",
"thumbnail" : "folder2/thumb.svg",
"text": "blah blah blah"
},
{
"name" : "folder3",
"thumbnail" : "folder3/thumb.svg",
"text": "blah blah blah"
},
]
Is there a way to do it? Thanks.
Explain more:
For example I tried array("name" => array_map("basename", glob('./folders/*', GLOB_ONLYDIR)),) and it just put all my folders as a giant array under one single entry of "name," like this {"name":["folder1","folder2","folder3"]}.
A pseudo solution:
IkoTikashi provided a solution, while not necessary answering the question, but could be useful to some people. I use his idea to establish some example codes below:
<?php
$checkfolder = './path/examples/folders';
$json = [];
foreach ( glob($checkfolder . '*', GLOB_ONLYDIR) as $folder)
{
$filename = $folder . "/description.txt";
if (file_exists($filename)) {
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
} else {
$contents = '';
}
$json[] = [
'name' => str_replace($checkfolder, '', $folder),
'thumb' => $folder . '/thumb.svg',
'text' => $contents
];
}
json_encode($json);
?>
Of course this solution isn't perfect. For one it doesn't provide usable url for thumbnails. And more importantly it erased the modularity of the original codes - that users can use three separated api to generate specific json to their need. The reason to reorganize the existing json files is that they can have an additional option to generate combined arrays. This solution, rather, created a whole new function to accomplish such goal - so while it is a temporary solution, it lacks of upgradability.
Read in all directories under folders/ and use them to set a new array:
<?php
$checkfolder = 'img/';
$json = [];
foreach ( glob($checkfolder . '*', GLOB_ONLYDIR) as $folder)
{
$folderName = str_replace($checkfolder, '', $folder);
$json[] = [
'name' => $folderName,
'thumbnail' => $folderName . '/thumb.svg',
'text' => 'blah blah blah'
];
}
print_r(json_encode($json));
Inside of that loop you would do file existance checks, reading the text etc.
json in general is a text, so, if you want to make your script a JSON data source, you are able to print it out in that format.
For example:
echo "{\n";
echo "{\n";
echo "'name':'$folderArr[0]'\n";
echo "}\n";
echo "}\n";
However, you must get sure that there's no any other text printout will be occurred on the script to avoid corruption of JSON format.

Netsuite PHP ItemSearchBasic problems

I am trying to return all inventory from a certain warehouse in Netsuite. I am having some issues and was wondering if anyone could point me in the right direction. The internalId of the warehouse I am trying to query is 16. When I do the search it returns 0 items - but doesn't fail.
Here is the PHP code I am working with.
<?php
require_once 'PHPtoolkit.php';
require_once 'login_info.php';
global $myNSclient;
$internalID = '16'; //Internal ID of the warehouse I want to query to see what inventory it has
$inventorySearch = new nsComplexObject("ItemSearchBasic");
$searchValue = new nsRecordRef(array('type' => 'location', 'internalId' => $internalID ));
$multiSelect = new nsComplexObject('SearchMultiSelectField');
$multiSelect->setFields(array('operator'=>'anyOf','searchValue'=>$searchValue,"operatorSpecified" => true));
$inventorySearch->setFields(array('location'=>$multiSelect));
try
{
$searchResponse = $myNSclient->search($inventorySearch);
$totalRecords = $searchResponse->totalRecords;
if ($totalRecords > 0)
{
echo "records found";
foreach ($searchResponse->recordList as $record)
{
echo "<pre>";
print_r($record);
echo "</pre>";
}
}
else
{
echo "No result found.";
}
}
catch (Exception $e)
{
echo $e;
echo "Item is not found. Please try again.";
exit();
}
Here is the SOAP request
<?xml version="1.0" encoding="UTF-8" ?>
- <Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:core_2011_2.platform.webservices.netsuite.com" xmlns:ns2="urn:common_2011_2.platform.webservices.netsuite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="urn:messages_2011_2.platform.webservices.netsuite.com">
- <Header>
- <passport actor="http://schemas.xmlsoap.org/soap/actor/next">
<email>xxxxx</email>
<password>[Content Removed for Security Reasons]</password>
<account>xxxxxx</account>
<role internalId="3" xsi:type="RecordRef" />
</passport>
</Header>
- <Bod
y>
- <search>
- <searchRecord xsi:type="ItemSearchBasic">
- <location operator="anyOf">
<searchValue internalId="16" type="location" />
</location>
</searchRecord>
</search>
</Body>
</Envelope>
$inventorySearch = new nsComplexObject("ItemSearchBasic");
$inventorySearch->setFields(array(
"location" => array(
"operator" => "anyOf",
"searchValue" => array(
"type" => "location",
"internalId" => $internalId
)
)
));
Then, do your try/catch.
But as I look at this, you are wanting to get item availability. That's a completely different call.
$filter = new nsComplexObject ( 'ItemAvailabilityFilter' );
$filter->setFields ( array (
"location" => array (
"operator" => "anyOf",
"searchValue" => new nsRecordRef ( array (
"type" => "location",
"internalId" => $internalId
) )
)
) );
I've spent significant amount of time building my own custom search using PHPToolKit v2011.2 endpoint, and got them to work after pulling my hair out as there aren't that many examples. With introduction of v2012_2 endpoint, things have changed and I have to relearn the things that I solved before. I "strongly" suggest that you use SAVED SEARCH, instead of trying to invent the way to do all your searches in PHP. Create a saved search in Netsuite, and call the SAVED SEARCH from your PHP with internalId of the search you created.

How to generate JSON data with PHP?

CREATE TABLE Posts
{
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
url VARCHAR(200)
}
json.php code
<?php
$sql=mysql_query("select * from Posts limit 20");
echo '{"posts": [';
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
echo '
{
"title":"'.$title.'",
"url":"'.$url.'"
},';
}
echo ']}';
?>
I have to generate results.json file.
To generate JSON in PHP, you need only one function, json_encode().
When working with database, you need to get all the rows into array first. Here is a sample code for mysqli
$sql="select * from Posts limit 20";
$result = $db->query($sql);
$posts = $result->fetch_all(MYSQLI_ASSOC);
then you can either use this array directly or make it part of another array:
echo json_encode($posts);
// or
$response = json_encode([
'posts' => $posts,
]);
if you need to save it in a file then just use file_put_contents()
file_put_contents('myfile.json', json_encode($posts));
Use this:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
You can create the myfile.json before you run the script.But its not compulsory if you have full sudo privileges(read/write permissions(For of you on Mac).
Here is a working Example:
<?php
// data stored in an array called posts
$posts = Array (
"0" => Array (
"id" => "01",
"title" => "Hello",
),
"1" => Array (
"id" => "02",
"title" => "Yoyo",
),
"2" => Array (
"id" => "03",
"title" => "I like Apples",
)
);
// encode array to json
$json = json_encode($posts);
$bytes = file_put_contents("myfile.json", $json); //generate json file
echo "Here is the myfile data $bytes.";
?>
Insert your fetched values into an array instead of echoing.
Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.
If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.
my_json.php
$array = array(
'title' => $title,
'url' => $url
);
echo json_encode($array);
Then in your script set the path to the file my_json.php
Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.
$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT)); // here it will print the array pretty
fclose($fp);
Hope it will works for you....
You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.
First, you need to decode it :
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);
Then change the data :
$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
if ($entry['activity_code'] == '1') {
$data[$key]['activity_name'] = "TENNIS";
}
}
Then re-encode it and save it back in the file:
$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
copy
Use PHP's json methods to create the json then write it to a file with fwrite.

Categories