This is my PHP file named testClient
**public function getXML() {
$xml = simplexml_load_file('https:/.............');
$feed1 = '<h3>' . $xml->channel->title . '</h3>';
foreach ($xml->channel->item as $item) {
$feed1 .= '<h4>' . $item->title . "</h4>";
}
$xml = simplexml_load_file('https://rumble.com/rss.php?target=sprinklevideo');
$feed2 = '<h3>' . $xml->channel->description . '</h3>';
foreach ($xml->channel->item as $item) {
$feed2 .= '<h4>' . $item->description . "</h4>";
}
$xml = simplexml_load_file('https://rumble.com/rss.php?target=sprinklevideo');
$feed3 = '<h3>' . $xml->channel->link . '</h3>';
foreach ($xml->channel->item as $item) {
$feed3 .= '<h4>' . $item->link . "</h4>";
}
return $feed1;
}**
This is my controller class where i want to viewing the result
**
use VideoBundle\VideoProviderClient\testClient as testClient;
class MainController extends Controller
{
public function MainAction() {
$zoo = new testClient();
$val = $zoo->getXML();
//dump
echo "<pre>";
var_dump($val);
echo "</pre>";
die();
return new Response("$val");
}
public function setVal($val) {
$this->item = json_encode($val);
return $this;
}
public function getVal() {
if ($this->item) {
return json_decode($val);
}
return null;
}
**
If i want to fetch data from RSS feed like title/description/link, i am getting those. But HOW CAN I GET ALL THOSE DATA AS A JSON OBJECT. Because in rss feed the data is saving as a item.
This is a sample "item" data from RSS feed ---
**
<item>
<title>Newlyweds stun guests with epic first dance</title>
<description>
your foot in time to the music!
</description>
<link>
https://zzx.com/v2zl27-bride-and-groom-perform-the-best-first-dance-ever-to-a-swingin-classic.html
</link>
<guid isPermaLink="false">media/8.5087</guid>
<pubDate>2015-06-03 12:49:16</pubDate>
<media:category scheme="http://search.yahoo.com/mrss/category_schema">viral</media:category>
<media:keywords>
viral videos, inspiring first wedding dance, songs for first wedding dance
</media:keywords>
<media:thumbnail url="https://rumble.com/rss/8-5019487.jpg" />
<media:player url="https://asdas.com/bin/8_8" height="426" width="491" />
<media:content url="https://i.rmbl.ws/s8/d99" type="video/mp4" />
</item>
**
Thanks in advance ...
You are adding HTML to your data on the first step. You should do that at the end. And the best option would be with a Twig template.
Then parsing XML to a JSON is quite simple:
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
Related
I am having a hard time trying to understand why I can't compare the values of two arrays in PHP. If I echo both of these during the loop using "echo $description->ItemDesriptionName;" and "echo $item->ItemName;" the values seem to show as the same, but when I try to compare them using if, nothing works. What am I missing?
<?php
$xml=simplexml_load_file("test.xml") or die("Error: Cannot create object");
$categories = $xml->Menu->Categories;
$items = $xml->Menu->Categories->Items->ItemObject;
$itemdescription = $xml->Menu->Options->Description->DescriptionObject;
foreach($items as $item) {
echo $item->ItemName . ' - ' . $item->Price . '</br>';
foreach ($itemdescription as $description) {
if ($description->ItemDescriptionName == $item->ItemName) {
echo 'We have a match!';
//where I would echo $description->ItemDescription;
}
}
}
?>
Here is the XML file
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Menu>
<Categories>
<Name>Category 1</Name>
<Items>
<ItemObject>
<ItemName>Item 1</ItemName>
<Price>1</Price>
</ItemObject>
<ItemObject>
<ItemName>Item 2</ItemName>
<Price>3</Price>
</ItemObject>
</Items>
</Categories>
<Options>
<Description>
<DescriptionObject>
<ItemDescriptionName>Item 1</ItemDescriptionName>
<ItemDescription>A Great item</ItemDescription>
</DescriptionObject>
<DescriptionObject>
<ItemDescriptionName>Item 2</ItemDescriptionName>
<ItemDescription>A Great item as well</ItemDescription>
</DescriptionObject>
</Description>
</Options>
</Menu>
</Root>
compare as string
and you have typo in ItemDescriptioName (ItemDescriptionName)
if ( (string)$description->ItemDescriptionName == (string)$item->ItemName) {
Convert to string and then compare
<?php
$xml=simplexml_load_file("test.xml") or die("Error: Cannot create object");
$menu = $xml->Menu;
$categories = $xml->Menu->Categories;
$items = $xml->Menu->Categories->Items->ItemObject;
$itemdescription = $xml->Menu->Options->Description->DescriptionObject;
foreach($items as $item) {
$itemname = $item->ItemName;
foreach ($itemdescription as $description) {
$descriptionname = $description->ItemDescriptionName ;
echo $itemname." ---- ".$descriptionname."<br/>";
if((string)$itemname === (string)$descriptionname){
echo "Yes its matched";
}
}
}
?>
Working fine for me
The properties like $description->ItemDescriptionName are SimpleXMLElement objects. So you do not compare strings but two objects.
SimpleXMLElement objects implement the magic method __toString(). They can be cast to string automatically, but a compare between to objects will not trigger that. You can force it:
if ((string)$description->ItemDescriptionName === (string)$item->ItemName) {
...
Can you access them directly instead using an accordant index?
...
$items = $xml->Menu->Categories->Items->ItemObject;
$itemdescription = $xml->Menu->Options->Description;
$i = 0;
foreach ($items as $item) {
echo $i.' '.$item->ItemName . ' - ' . $item->Price;
echo $itemdescription->DescriptionObject[$i]->ItemDescriptionName[0];
echo ' ';
echo $itemdescription->DescriptionObject[$i]->ItemDescription[0];
echo '</br>';
$i++;
}
I am trying to access the 'field' element in the 'criteria' node in the following XML:
<?xml version="1.0" encoding="utf-8"?>
<result>
<product>
<data>
<field>spr_tech1</field>
<value>S7</value>
<criteria field="xfield_3">
<criteria_list>Green</criteria_list>
<criteria_list>Beige</criteria_list>
</criteria>
</data>
<data>
<field>spr_tech1</field>
<value>S1</value>
<criteria field="xfield_3">
<criteria_list>Red</criteria_list>
<criteria_list>Blue</criteria_list>
<criteria_list>Yellow</criteria_list>
</criteria>
</data>
<data>
<field>spr_tech1</field>
<value>S7</value>
<criteria field="xfield_3">
<criteria_list>Green</criteria_list>
</criteria>
<criteria field="tech_rt2">
<criteria_list>Transistor</criteria_list>
</criteria>
</data>
</product>
</result>
The code below results in the following error:
Fatal error: Call to a member function attributes() on a non-object
function parseXmlFile($filename)
{
$xml = file_get_contents($filename);
$obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode($obj), true); // Convert to array}
return $array;
}
$xform = parseXmlFile('transformations.xml');
foreach ($xform['product']['data'] as $data)
{
echo (string)$data['field'] . '<br>';
echo (string)$data['value'] . '<br>';
foreach($data['criteria']->attributes() as $att => $val)
{ echo $att . ' = ' . $val . '<br>'; }
echo $data['criteria']->attributes()->{'field'} . '<br>';
foreach($data['criteria']['criteria_list'] as $att => $val)
{ echo $att . ' = ' . $val . '<br>'; }
echo "-----------------------------------<br>";
}
print "<pre>";
print_r($xform);
print "</pre>";
I've tried a couple methods as you can see in the code, but neither are working for me.
Any help is appreciated!
It seems the problem is when you load the file.
I tried it with file_get_contents() See below
$xml_content = file_get_contents('path to your XML file');
$xform = simplexml_load_string($xml_content);
foreach ($xform['product']['data'] as $data)
{
echo (string)$data['field'] . '<br>';
echo (string)$data['value'] . '<br>';
foreach($data['criteria']->attributes() as $att => $val)
{ echo $att . ' = ' . $val . '<br>'; }
echo $data['criteria']->attributes()->{'field'} . '<br>';
foreach($data['criteria']['criteria_list'] as $att => $val)
{ echo $att . ' = ' . $val . '<br>'; }
echo "-----------------------------------<br>";
}
print "<pre>";
print_r($xform);
print "</pre>";
Your parseXmlFile function can be replaced completely with the built-in simplexml_load_file():
it loads the contents with file_get_contents first; simplexml_load_file vs simplexml_load_string will do this for you
it forces the LIBXML_NO_CDATA option, which is almost certainly not something you need; to get the text contents of a SimpleXML object - including CDATA - you use (string)$node
it converts the incredibly useful SimpleXML object into an array that will be missing half of the data and much worse to work with
To understand SimpleXML, look at the examples in the manual. Elements are accessed with ->name and attributes with ['name'].
So:
$xform = simplexml_load_file('transformations.xml');
foreach ($xform->product->data as $data)
{
echo (string)$data->field . '<br>';
echo (string)$data->value . '<br>';
foreach($data->criteria->attributes() as $att => $val)
{ echo $att . ' = ' . $val . '<br>'; }
echo $data->criteria['field'] . '<br>';
foreach($data->criteria->criteria_list as $number => $node)
{ echo $number . ' = ' . (string)$node . '<br>'; }
echo "-----------------------------------<br>";
}
I'm trying to display values from this xml feed:
http://www.scorespro.com/rss/live-soccer.xml
In my PHP code I have the following loop but it does not display the results on my page:
<?php
$xml = simplexml_load_file("http://www.scorespro.com/rss/live-soccer.xml");
echo $xml->getName() . "<br>";
foreach($xml->children() as $item)
{
echo $item->getName() . ": " . $item->name . "<br>";
}
?>
For some reason it only shows:
rss
channel:
I'm fairly new to how XML works so any help would be much appreciated.
You can get actual data from $xml->channel->item so use like below
$items = $xml->channel->item;
foreach($items as $item) {
$title = $item->title;
$link = $item->link;
$pubDate = $item->pubDate;
$description = $item->description;
}
DEMO.
you can use below code
$dom = new DOMDocument;
$dom->loadXML($url);
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$xml = simplexml_import_dom($dom);
$data = $xml->channel->item;
I have an xml file that has different named nodes and multi level child nodes (that are different between each node.) How should I access the data? Will it require many nested for loops?
Here is a sample of the xml code:
<start_info>
<info tabindex="1">
<infonumber>1</infonumber>
<trees>green</trees>
</info>
</start_info>
<people>
<pe>
<people_ages>
<range number="1">
<age value="1">1</age>
<age value="2">2</age>
</range>
</people_ages>
</pe>
</people>
Here is my code so far:
$xml = simplexml_load_file("file.xml");
echo $xml->getName() . "start_info";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
Here is some example code that I hope can point you in the right direction. Essentially, it is walking the DOMDocument echoing the element name and values. Note that the whitespace between the elements is significant, so for the purposes of the demo, the XML is compacted. You may find a similar issue loading from a file, so if you are not getting the expected output you might need to strip whitespace nodes.
You could replace the //root/* with a different XPath for example //people if you only wanted the <people> elements.
<?php
$xml = <<<XML
<root><start_info><info tabindex="1"><infonumber>1</infonumber><trees>green</trees></info></start_info>
<people><pe><people_ages><range number="1"><age value="1">1</age><age value="2">2</age></range></people_ages></pe></people>
</root>
XML;
$dom = new DOMDocument();
$dom->recover = true;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$nodelist = $xpath->query('//root/*');
foreach ($nodelist as $node) {
echo "\n$node->tagName";
getData($node);
}
function getData($node) {
foreach ($node->childNodes as $child) {
if ($child->nodeType == XML_ELEMENT_NODE) {
echo ($child->tagName === '' ? '' : "\n").$child->tagName;
}
if ($child->nodeType == XML_TEXT_NODE) {
echo '->'.$child->nodeValue;
}
if ($child->hasChildNodes()) {
getData($child); // recursive call
}
}
}
?>
check this
$xml_file = 'file.xml';
$xmlobj = simplexml_load_file($xml_file);
echo $xmlobj->getName() . 'start_info<br />';
foreach($xmlobj->children() as $childs) {
echo $childs->getName(). ': '. '<br />';
if($childs->count()>1) {
foreach($childs as $child) {
echo $child->getName(). ': '. $child. '<br />';
}
}
}
http://www.managerleague.com/export_data.pl?data=transfers&output=xml&hide_header=0
These are player sales from a browser game. I want to save some fields from these sales. I am fetching that xml with curl and storing on my server. Then do the following:
$xml_str = file_get_contents('salespage.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/transfer');
print_r($items);
foreach($items as $item) {
echo $item['buyerTeamname'], ': ', $item['sellerTeamname'], "\n";
}
The array is empty and i cant seem to get anything from it. What am i doing wrong?
There is no reason to use cURL or XPath for that. You can do
$url = 'http://www.managerleague.com/export_data.pl?data=transfers&output=xml&hide_header=0';
$transfers = new SimpleXMLElement($url, NULL, TRUE);
foreach($transfers->transfer as $transfer) {
printf(
"%s transfered from %s to %s\n",
$transfer->playerName,
$transfer->sellerTeamname,
$transfer->buyerTeamname
);
}
Live Demo
You forgot a slash in your xpath:
$xml_str = file_get_contents('salespage.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('/*/transfer');
print_r($items);
foreach($items as $item) {
echo $item->buyerTeamname, ': ', $item->sellerTeamname, "\n";
}
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>
Is this what you want?