This question already has answers here:
Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?
(2 answers)
Closed 12 months ago.
Im having a problem getting a namespaced (Or semi-colin') item with PHP's SimpleXML. I've done a little digging through google and tried the likes if asXML but im back at square one.
The part I can't get < content:encoded >
http://content.sportsdatallc.com/?feed=rss2&cat=364
PHP
$xml = new SimpleXMLElement($response, LIBXML_NOCDATA);
print_r($xml);
I can get all the nodes that I need, except for that piece above. If i print_r it doesnt showup.
I have also tried this:
$xml = new SimpleXMLElement($response, LIBXML_NOCDATA);
foreach ($xml->channel->item as $item)
{
echo 11;
$art = $item->children('content:encoded');
print_r($art);
}
Simple solution str_replace the content:encoded with content.
$xml = str_replace('content:encoded>', 'content>', $xml);
It may not be the best solution but it is simple and it works :)
You need:
foreach($xml->channel->item as $item) {
$contentNodes = $item->children('content',true);
...
}
Take a look at namespaces for this class.
Related
This question already has answers here:
How to use XMLReader in PHP?
(7 answers)
Closed 6 years ago.
PHP developers here ??
I have a PHP function who parse an xml file (using DOMDocument, i'm proficien with this tool). I want to do the same with XMLReader, but i don't understand how XMLReader works...
I want to use XMLReader because it's a light tool.
Feel free to ask me others questions about my issue.
function getDatas($filepath)
{
$doc = new DOMDocument();
$xmlfile = file_get_contents($filepath);
$doc->loadXML($xmlfile);
$xmlcars = $doc->getElementsByTagName('car');
$mycars= [];
foreach ($xmlcars as $xmlcar) {
$car = new Car();
$car->setName(
$xmlcar->getElementsByTagName('id')->item(0)->nodeValue
);
$car->setBrand(
$xmlcar->getElementsByTagName('brand')->item(0)->nodeValue
);
array_push($mycars, $car);
}
return $mycars;
}
PS : I'm not a senior PHP dev.
Ahah Thanks.
This is a good example from this topic, I hope it helps you to understand.
$z = new XMLReader;
$z->open('data.xml');
$doc = new DOMDocument;
// move to the first <product /> node
while ($z->read() && $z->name !== 'product');
// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
// either one should work
//$node = new SimpleXMLElement($z->readOuterXML());
$node = simplexml_import_dom($doc->importNode($z->expand(), true));
// now you can use $node without going insane about parsing
var_dump($node->element_1);
// go to next <product />
$z->next('product');
}
XMLReader does not, as far as I can tell, have some equivalent way of filtering by an element name. So the closest equivalent to this would be, as mentioned in rvbarreto's answer, to iterate through all elements using XMLReader->read() and grabbing the info you need when the element name matches what you are wanting.'
Alternatively, you might want to check out SimpleXML, which supports filtering using XPath expressions, as well as seeking to a node in the XML using the element structure like they are sub-objects of the main object. For instance, instead of using:
$xmlcar->getElementsByTagName('id')->item(0)->nodeValue;
You would use:
$xmlcar->id[0];
Assuming all of your car elements are at the first level of the XML document tree, the following should work as an example:
function getDatas($filepath) {
$carsData = new SimpleXMLElement($filepath, NULL, TRUE);
$mycars = [];
foreach($carsData->car as $xmlcar) {
$car = new Car();
$car->setName($xmlcar->id[0]);
$car->setBrand($xmlcar->id[0]);
$mycars[] = $car;
}
}
This question already has answers here:
SimpleXML: Selecting Elements Which Have A Certain Attribute Value
(2 answers)
Closed 8 years ago.
I have XML-file and i try to get value. I need value 12345 from variable media_id. How i can get it with php and simplexml?
<?xml version="1.0" encoding="UTF-8"?>
<Playerdata>
<Clip>
<MediaType>video_episode</MediaType>
<Duration>5400</Duration>
<PassthroughVariables>
<variable name="media_type" value="video_episode"/>
<variable name="media_id" value="12345"/>
</PassthroughVariables>
</Clip>
</Playerdata>
I have now only:
$xml = simplexml_load_file("file.xml");
Try this:
$xml = simplexml_load_file("file.xml");
$variable = $xml->xpath('//variable[#name="media_id"]')[0];
echo $variable["value"];
You can load your XML file into Simplexml which will parse it and return an SimpleXML object.
$xml = simplexml_load_file('path/to/file.xml');
//then you should be able to access the data through objects
$passthrough = $xml->Clip->PassthroughVariables;
//because you have many children in the PassthroughVariables you'll need to iterate
foreach($passthrough as $p){
//to get the attributes of each node you'll have to call attributes() on the object
$attributes = $p->attributes();
//now we can iterate over each attribute
foreach($attributes as $a){
//SimpleXML will assume each data type is a SimpleXMLElement/Node
//so we need to cast it for comparisons
if((String)$a->name == "media_id"){
return (int)$a->value;
}
}
}
The SimpleXMLElement documentation is probably a good starting point when it comes to working with the SimpleXMLObject. http://uk1.php.net/manual/en/class.simplexmlelement.php
Here is w/o Xpath
$xml = simplexml_load_file('file.xml');
$value = (int) $xml->Clip->PassthroughVariables->variable[1]['value'];
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am currently using the following code, but no result is returned:
<?php
$url = 'http://myknowledge.org.uk/xml';
$xml = new SimpleXMLElement(file_get_contents($url));
foreach ($xml->item as $item) {
$title = $item->title;
}
echo $title;
?>
The XML Code:
<?xml version="1.0" encoding="utf-8"?>
<item>
<title>Apple</title>
<notableFor>Fruit</notableFor>
<wikiid>Apple</wikiid>
<description>The apple is the pomaceous fruit of the apple tree, Malus domestica of the rose family. It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans.</description>
<img></img>
<website></website>
<translate>
<de>Äpfel</de>
<fr>pomme</fr>
<it>mela</it>
<es>manzana</es>
<ru>яблоко</ru>
</translate>
<nutritionalInfomation name="Apple" quantity="100g">
<calories>52</calories>
<carb>14</carb>
<fibre>2.4</fibre>
<protein>0.3</protein>
<fat>0.2</fat>
</nutritionalInfomation>
</item>
If anybody has an idea how to fix this I would love to know. Thanks.
The XML appears to be invalid in lines 4 and 5:
<notableFor>Fruit</title>
<wikiid>Apple</title>
Which should be:
<notableFor>Fruit</notableFor>
<wikiid>Apple</wikiid>
I recommend using the XML validator at http://www.w3schools.com/xml/xml_validator.asp to debug errors with your XML code.
Also, as your root element is item, you may want to change your PHP code:
<?php
$url = 'http://myknowledge.org.uk/xml';
$item = new SimpleXMLElement(file_get_contents($url));
$title = $item->title;
$description = $item->description;
?>
(I don't have a copy of PHP on hand to test this, but according to http://php.net/manual/en/simplexml.examples-basic.php, this should work)
Xml can have only 1 root element, in your example the root is item
When loading to SimpleXML you can get the root name with $xml->getName()
$url = 'http://myknowledge.org.uk/xml';
$item = new SimpleXMLElement($url, null, true);
$title = $item->title;
$description = $item->description;
Or you should enclose you items in another root i.e items if you need multiple
This question already has answers here:
SimpleXML: Selecting Elements Which Have A Certain Attribute Value
(2 answers)
Implementing condition in XPath [duplicate]
(2 answers)
Closed 9 years ago.
I am trying to parse out the value of a node I am referencing by one of its attributes. but I am not sure of the syntax
XML:
<data>
<poster name="E-Verify" id="everify">
<full_image url="e-verify-swa-poster.jpg"/>
<full_other url=""/>
</poster>
<poster name="Minimum Wage" id="minwage">
<full_image url="minwage.jpg"/>
<full_other url="spa_minwage.jpg"/>
</poster>
</data>
here is where I want to get the url value of full_image where poster id equal to minwage:
$xml = simplexml_load_file('PosterData.xml');
$main_url = $xml->full_image[name] where poster[id] = "minwage";
//something like that.
echo $main_url;
Result: minwage.jpg
If anyone has any resources that cover this stuff please share.
You should be able to use SimpleXMLElement::xpath() to run an xpath query on a simple XML document.
$xml = simplexml_load_file('PosterData.xml');
$main_url = $xml->xpath('name[#id="minwage"]/full_image')[0];
echo $main_url;
Simply loop the poster elements and remember to cast the attribute values to strings, since you want to compare them (and probably output them) as strings:
$xml = simplexml_load_file('PosterData.xml');
foreach ($xml->poster as $poster) {
if ((string) $poster['id'] == 'minwage') {
echo (string) $poster->full_image['url'];
}
}
You can use:
$object = simplexml_load_string('<data><poster name="E-Verify" id="everify"><full_image url="e-verify-swa-poster.jpg"/><full_other url=""/></poster><poster name="Minimum Wage" id="minwage"><full_image url="minwage.jpg"/><full_other url="spa_minwage.jpg"/></poster></data>');
foreach ($object as $value) {
echo "URL: ".$value->full_image->attributes();
echo "<br>";
}
Either use simplexml_load_file('Some external file.xml') if calling external file.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I get an element's serialised HTML with PHP's DOMDocument?
PHP + DOMDocument: outerHTML for element?
I am trying to extract all img tags from a string. I am using:
$domimg = new DOMDocument();
#$domimg->loadHTML($body);
$images_all = $domimg->getElementsByTagName('img');
foreach ($images_all as $image) {
// do something
}
I want to put the src= values or even the complete img tags into an array or string.
Use saveXML() or saveHTML() on each node to add it to an array:
$img_links = array();
$domimg = new DOMDocument();
$domimg->loadHTML($body);
$images_all = $domimg->getElementsByTagName('img');
foreach ($images_all as $image) {
// Append the XML or HTML of each to an array
$img_links[] = $domimg->saveXML($image);
}
print_r($img_links);
You could try a DOM parser like simplexml_load_string. Take a look at a similar answer I posted here:
Needle in haystack with array in PHP