How would I go about traversing this JSON object? - php

How would I access the [0] -> Array() located below and retrieve the [title] which is "Spirited Away" by iterating over the array?
Array
(
[#attributes] => Array
(
[version] => 2.0
)
[channel] => Array
(
[title] => Site Title
[link] => site/
[language] => en-us
[category] => All
[image] => Array
(
[title] => Site
[url] => http://example.com
[link] => example.com
)
[item] => Array
(
[0] => Array
(
[title] => Spirited Away
[pubDate] => date
[category] => Movies
[link] => linkhere
[enclosure] => Array
(
[#attributes] => Array
(
[url] => someurlhere
[length] => length
[type] => application/x-bittorrent
)
)
I'm currently trying to iterate over the array using a foreach loop but It's outputting nothing. I would post my code but the code section of this question is already too long. I'm using PHP and nothing I have tried so far was working.
This JSON code was generated from an XML document using json_encode and then decoded using json_decode into a JSON object.

comment to answer as its correct.
to loop through this particular array structure its:
foreach ( $array['channel']['item'] as $x){
echo $x['title'];
}

Related

Trying to extract an xml file stored as a blob from a database and storing the extracted xml data in a php object

I currently have a database which contains xml files stored as blobs. When I attempt to extract this data using sql I am not getting the data in the original xml format rather just bits of text from the xml file. I have tried a number of ways but no luck so far anyone have any ideas on how to do this?
The aim is to determine which xml file is needed for comparison, to retrieve it from the database and compare it to another xml file.
Heres one thing I've been trying:
**//************THIS IS WHERE THE PROBLEM IS*************************
if($databaseMatchedModelsObjects[$count] -> version == $maxVersion && $databaseMatchedModelsObjects[$count] -> release == $maxRelease){
$con2 = connect2();
$contentModel = $con2->prepare("SELECT fileName, type, size, content FROM model WHERE id=:id LIMIT 1");
//print_r($databaseMatchedModelsObjects[$count] -> mid);
$contentModel->bindParam('id',$databaseMatchedModelsObjects[$count] -> mid,PDO::PARAM_INT);
$contentModel->execute(array('id'=>$databaseMatchedModelsObjects[$count] -> mid));
$row = $contentModel->fetch();
//$sql_statement= "SELECT xmltype(content, nls_charset_id('CHAR_CS')).getclobval() rfile FROM model WHERE id =" . $databaseMatchedModelsObjects[$count] -> id;
//$sql_result = mysqli_query($con, $sql_prim);
//print_r($sql_result);
//if($row = #mysqli_fetch_array($result)) {
if($row) {
$finalModelToCompareTo = $row['content'];
//echo(simplexml_load_string());
//print_r(simplexml_load_string($finalModelToCompareTo));
//print_r($finalModelToCompareTo);
//$finalModelToCompareTo = $databaseMatchedModelsObjects[$count] -> content;
//print_r($databaseMatchedModelsObjects[$count] -> content);
}
}
Example print out using var dump of the content, just a snippet full print out is too long. This should be in xml format.
string(15513) " G title sub title 0 English 0 date This is the top level of the Common Information Model. This model contains the singleton, root Managed Object Class (MOC) ManagedElement under which the complete model is contained. Directly under ManagedElement are managed-function level classes SF, T, E and the root MOC of any managed functions. The Equipment Root MOC is in the Equipment Managed Object Model (MOM). The root MOC for a managed function is hosted in the managed function MOM. Deprecated, Contains product information for a Managed Element and ManagedFunction(s). Replaced by ProductData The product number in ABC format. For information, refer to Corporate Basic Standards. The product revision in the form R[1-9][A-Z]. For information, refer to Corporate Basic Standards. Common product name.
XML File that I will be comparing against Sample code:
How it is printed in comparison:
$uploaded_model = #simplexml_load_file($targetdir . "\\" . $fileinfo->getFilename()); print_r($uploaded_model);
SimpleXMLElement Object ( [dtdVersion] => G [momMetaData] => SimpleXMLElement Object ( [momTitle] => title [momSubTitle] => sub title [momIdentity] => SimpleXMLElement Object ( [docNum] => 0 [docLang] => English [docRev] => 0 [docDate] => date ) [createdBy] => SimpleXMLElement Object ( [signature] => xqichen ) ) [mim] => SimpleXMLElement Object ( [#attributes] => Array ( [author] => XQHE [contact] => ok#dektech.com.au [correction] => 0 [date] => 2014-11-22 [docNo] => [name] => CmwPm [namespace] => urn:com:CmwPm [namespacePrefix] => cmwpm [organization] => XDT/DEK [release] => 2 [revision] => A [version] => 2 ) [description] => Performance Management MOM. 3GPP defines Performance Management in 3GPP 32.401. [domainExtension] => SimpleXMLElement Object ( [#attributes] => Array ( [domain] => ECIM ) [extension] => Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => MomName [value] => PM ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => Version [value] => 2 ) ) [2] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => ecimMomRelease [value] => 3 ) ) [3]
=> SimpleXMLElement Object ( [#attributes] => Array ( [name] => ecimMomCorrection [value] => 0 ) ) [4] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => immNamespace [value] => MOM_NAME ) ) ) ) [implements] => SimpleXMLElement Object ( [#attributes] => Array ( [correction] => 0 [name] => ECIM_PM [release] => 3 [version] => 2 ) ) [struct] => Array ( [0] => SimpleXMLElement Object ( [#attributes]
=> Array ( [name] => MeasurementReaderNameValue ) [description] => This name value is used for real-time monitoring. The real-time monitoring is set up using a PM job of type REALTIMEJOB. [structMember] => Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => currentValue ) [description] => Contains the real-time value of the measurement. This value can be read in conjunction with attribute lastUpdated to determine the value of counters in real time. [string] => SimpleXMLElement Object ( ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => lastUpdated ) [description] => Contains the exact time the currentValue was last set. This attribute is used to determine how recent the value supplied in currentValue is. [derivedDataTypeRef] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => DateTime ) [mimName] => CmwPm ) )
I managed to fix my problem by:
$xml = simplexml_load_string($finalModelToCompareTo);
The XML seems to have been converted to string within the blob and you need to use this method to convert it back to a SimpleXMLObject again.
I think it really IS a XML file. The string(15513) " G title sub title 0 En... representation is the same XML file parsed by the browser and you only see the plaintext values but not the XML tags. So, don't worry about the losses you see in the printout. If you open up the webpage source using Ctrl+U you can see the complete XML file syntax.

embed php tags to display xml from url

I have been working on this sports website as kind of a learning project.
I have a table laid out in html to organize the xml data
I am using this script to pull live data from a remote server that provides it in xml.
<?php
$url = "http://xml.feed.com";
$xmlinfo = simplexml_load_file($url);
print_r($xmlinfo);
?>
This is the first time I have ever use php so any advice/criticism would be greatly appreciated and excepted.
Here is a sample of simpleXML.
SimpleXMLElement Object
(
[params] => SimpleXMLElement Object
(
[#attributes] => Array
(
[legend] => False
[catId] => -1
[sportId] => -1
[matchId] => -1
[delta] => 60
[deltaUtc] => 2014-01-25T00:35
[utc] => 2014-01-25T01:35
[includeCent] => False
[includeFraction] => False
)
)
[data] => SimpleXMLElement Object
(
[s] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 1
[n] => American Football
)
[cat] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 1109
[n] => NFL Pro Bowl
)
[m] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 1015211
[n] => Team Rice v Team Sanders
[mid] => 573422
[rot] => 495
[dt] => 2014-01-27T00:30
)
[t] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 1
[n] => Single Match
)
[l] => Array
(
[0] => Team Rice
[1] => Team Sanders
)
I have been trying to figure out how to display this xml data using php tags embedded in the html code..
So I have 2 questions.
How would these tags be written?
And, Am I heading in the right direction as far as my approach using php embedded in html?
Thanks much in advance! And I hope I was clear enough...

I'm trying to find an attribute using simpleXML

I have a simpleXML output of:
SimpleXMLElement Object
(
[#attributes] => Array
(
[version] => 2
)
[currentTime] => 2013-02-05 21:26:09
[result] => SimpleXMLElement Object
(
[rowset] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => characters
[key] => characterID
[columns] => name,characterID,corporationName,corporationID
)
[row] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Wrytha Cy
[characterID] => 209668693
[corporationName] => Deep Core Mining Inc.
[corporationID] => 1000006
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Eve Mae
[characterID] => 624980803
[corporationName] => Viziam
[corporationID] => 1000066
)
)
[2] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Wrytha
[characterID] => 709227913
[corporationName] => The Flying Tigers
[corporationID] => 669350666
)
)
)
)
)
[cachedUntil] => 2013-02-05 21:35:04
)
I would like to loop through with my php loop and get "name' and "characterID". I've trying something like:
$simpleXML = simplexml_load_string($xml);
foreach ($simpleXML->result->rowset->row as $row) {
print_r($row);
$name = $row['#attributes']['name'];
echo $name.'<br>';
}
but $name is not being set. It's gonna be something simple, just not seeing it in my haste and first time with simpleXML.
Attributes are accessed using the syntax $element['attribute_name'], so in your case, you need $row['name'].
It's important to remember that SimpleXML objects are kind of magic - the $element->child, $element_list[0] and $element['foo'] syntax overloads the normal PHP logic to be useful. Similarly, (string)$element will give you the full textual content of an element, however it is broken up in the actual XML.
As such, the print_r output will not give you a "real" view of the object, so should be used with care. There are a couple of alternative debug functions I've written here which give a more accurate idea of how the object will behave.

how to fetch this array using foreach loop

i have a multidimensional array. the array is returned by parsing xml using curl. when curl gave me the output i converted the output into array using $array = (array) simplexml_load_string($query); and the $array is given below. Now i want to fetch this array using foreach loop and want everything from this array
Array
(
[Meta] => SimpleXMLElement Object
(
[Query] => php programming
[ResultOffset] => SimpleXMLElement Object
(
)
[NumResults] => 25
[TotalResults] => 36839
)
[Slideshow] => Array
(
[0] => SimpleXMLElement Object
(
[ID] => 1966058
[Title] => title here
[Description] => description here
[Status] => 2
[Username] =>usrname
[URL] => url here
[ThumbnailURL] => a url
[ThumbnailSmallURL] => a url
[Embed] => some embed code
)
[1] => SimpleXMLElement Object
(
[ID] => 1966058
[Title] => title here
[Description] => description here
[Status] => 2
[Username] =>usrname
[URL] => url here
[ThumbnailURL] => a url
[ThumbnailSmallURL] => a url
[Embed] => some embed code
)
and continue
You can retrieve meta information without using foreach:
echo $array['Meta']->Query;
echo $array['Meta']->NumResults;
and so on...
To fetch slideshows:
foreach($array['Slideshow'] as $slideshow)
{
echo $slideshow->ID;
echo $slideshow->Title;
//-- and so on...
}
If you want to retrieve the ID and Titles of each SimpleXMLElement Object, try this:
<?php
forach ($array['Slideshow'] as $simpleXMLelem) {
echo $simpleXMLelem->getId();
echo $simpleXMLelem->getTitle();
}

combine XML objects PHP

It's pretty straightforward, I have an array with a number of nodes of the same structure available as Simple XML objects (extracted from different XML documents). What's the easiest way to add them to a single XML document, so I can output the combined XML? I've searched, but I can't find a good solution.
Edit: Array looks like this, how do I combine these objects in one single XML object?
Array (
[0] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[no] => 23432423
[type] => Array
)
[id] => 40043030
[title] => Cars
[cinemadate] => 2011-07-06
[changedate] => 2011-07-27T10:19:00
[year] => 2011
[length] => 112
[genres] => SimpleXMLElement Object
(
[genre] => animatie
)
[1] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[no] => 48050593
[type] => Array
)
[id] => 1231676
[title] => Arrietty
[cinemadate] => 2011-07-06
[changedate] => 2011-06-21T10:39:00
[genres] => SimpleXMLElement Object
(
[genre] => animatie
)
Iterate over the array and add the data to the existing simplexml object. You have not provided much information in your question how the array data looks like nor have you provided an example simplexml object / xml chunk, so there is not much more to say specifically.

Categories