PHP Object - how can I access this value - php

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

Related

PHP object operator building string within foreach?

I am trying to build an object that will hold multiple objects based of iterating through an array:
<?php
$final_object = new stdClass();
$array = ['one','two'];
$temp_str = '';
foreach ($array as $value) {
$temp_str .= $value . '->';
}
$temp_str = rtrim($temp_str, '->');
$final_object->$temp_str = 999;
print_r($final_object);
exit;
As you can guess, the parser treats '->' as a string literal and not a PHP object operator.
Is what I am attempting to do possible?
Eventually, I want to build a json string after json_encoding to: {"one":{"two": 999}}
You could store a reference of the object during the loop and assign your value at the end:
$final_object = new stdClass();
$array = ['one','two'];
$ref = $final_object ;
foreach ($array as $value) {
$ref->$value = new stdClass() ;
$ref = &$ref->$value ; // keep reference of last object
}
$ref = 999; // change last reference to your value
print_r($final_object);
Outputs:
stdClass Object
(
[one] => stdClass Object
(
[two] => 999
)
)
You could do the same using arrays:
$array = ['one','two'];
$final_object = [];
$ref =& $final_object;
foreach ($array as $value) {
$ref[$value] = [];
$ref =& $ref[$value];
}
$ref=999;
echo json_encode($final_object);
Outputs:
{"one":{"two":999}}

JSON and Arrays mixed up (in PHP)

This is what I get from my SQL selection. The data is correct, now I'd like to echo it by foreach.
Array ( [0] => stdClass Object ( [sql_column] => [{"1":"value1", "2":"value2", "3":"value3"}] ) )
What I've tried (and which didn't work) was:
$obj = json_decode($arr);
foreach($obj as $data){
echo $data->sql_column->1; //this should echo "value1", but it doesn't
}
Does anyone see my mistake? Thanks in advance!
If $arr is the array you posted then you can't json_decode it since it's an array and not a JSON string.
//First you need to get the string
$json = $arr[0]->sql_column;
//Then decode
$data = json_decode($json);
//Then loop
foreach($data as $key => $value){
echo "$key = $value \n";
}
Your json seems to be complicated (double dimensional array), but you can fetch values from it in this manner:
foreach($arr as $data){
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}
}
I hope you get an idea...
I used foreach for $arr to cover multi values, you can omit that if you want:
$data=$arr[0];
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}

Looping through PHP array in foreach and give each $value a new variable name

I want to take an array, loop it with a foreach loop, and have each array value be sent through a class to get data from a database. This is the code I am currently using:
foreach ($unique_category as $key => $value)
{
$category = $value;
$value = new database;
$value->SetMysqli($mysqli);
$value->SetCategory($category);
$value->query_category();
${"$value_category"} = $value->multi_dim_array();
print_r(${"$value_category"});
echo "<br /><br />";
}
print_r($unique_category[0]."_category");
I want the variable $unique_category[0]."_category" to be ${"$value_category"}.
Currently, the ${"$value_category"} in the foreach loop prints out the correct value/array, while $unique_category[0]."_category" just prints person_category (person being the first value in that array).
How would I go about making $unique_category[0]."_category" print the same thing as ${"$value_category"}?
Thank you
EDIT:
The foreach loop is making a multidimensional array that looks something like this Array ( [0] => Array ( [0] => Home [1] => 9.8 ) [1] => Array ( [0] => Penny [1] => 8.2 )) I want to be able to print out this array outside the foreach loop, with each md array having its own variable name so I can print them out wherever and whenever I want.
Testing without the object
<?php
$unique_category_list = array('foo', 'bar', 'baz');
foreach ($unique_category_list as $key => $value)
{
$category = $value;
$value_category = $value."_".$category;
$unique_category = $unique_category_list[$key]."_category";
$unique_category = ${"$value_category"} = $key;
print_r($unique_category_list[$key]."_category");
echo "\n\n";
}
?>
Outputs:
foo_category
bar_category
baz_category
With the object
<?php
// note that $unique_category is now $unique_category_list && $value is now $category
foreach ($unique_category_list as $key => $category)
{
$database = new Database();
$database->setMysqli($mysqli);
$database->setCategory($category);
$database->query_category();
// http://www.php.net/manual/en/language.oop5.magic.php#object.tostring
// this will invoke the `__toString()` of your $database object...
// ... unless you meant like this
// $value_category = $category."_".$category;
$value_category = $database."_".$category;
$unique_category = $unique_category_list[$key]."_category";
// http://stackoverflow.com/questions/2201335/dynamically-create-php-object-based-on-string
// http://stackoverflow.com/questions/11422661/php-parser-braces-around-variables
// http://php.net/manual/en/language.expressions.php
// // http://php.net/manual/en/language.variables.variable.php
// 'I want the variable $unique_category[0]."_category" to be ${"$value_category"}.'
$unique_category = ${"$value_category"} = $database->multi_dim_array();
}
print_r($unique_category_list[0]."_category");
echo "<br><br>\n\n";
?>

PHP parse assoc. array or XML

How to acces this assoc array?
Array
(
[order-id] => Array
(
[0] => 1
[1] => 2
)
)
as a result of XML parsing
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE request SYSTEM "http://shits.com/wtf.dtd">
<request version="0.5">
<order-states-request>
<order-ids>
<order-id>1</order-id>
<order-id>2</order-id>
...
</order-ids>
</order-states-request>
</request>
$body = file_get_contents('php://input');
$xml = simplexml_load_string($body);
$src = $xml->{'order-states-request'}->{'order-ids'};
foreach ($src as $order) {
echo ' ID:'.$order->{'order-id'};
// dont work - echoes only ID:1, why?
}
// ok, lets try just another way...
$items = toArray($src); //googled function - see at the bottom
print_r($items);
// print result - see at the top assoc array
// and how to acces order ids in this (fck) assoc array???
//------------------------------------------
function toArray(SimpleXMLElement $xml) {
$array = (array)$xml;
foreach ( array_slice($array, 0) as $key => $value ) {
if ( $value instanceof SimpleXMLElement ) {
$array[$key] = empty($value) ? NULL : toArray($value);
}
}
return $array;
}
MANY THANKS FOR ANY HELP!
What you want is:
$body = file_get_contents('php://input');
$xml = simplexml_load_string($body);
$src = $xml->{'order-states-request'}->{'order-ids'}->{'order-id'};
foreach ($src as $id)
{
echo ' ID:', $id, "\n";
}
Live DEMO.
What happens with your code is that you're trying to loop:
$xml->{'order-states-request'}->{'order-ids'}
Which is not the array you want, order-id is, as you can see on your dump:
Array
(
[order-id] => Array

How do I create variables from XML data in PHP?

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

Categories