This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
PHP xpath - find element with a value and also get elements before and after element
I have the following xml:
<Table>
<ID>100</ID>
<Name>Fridge</Name>
<Description>A cool refrigerator</Description>
</Table>
<Table>
<ID>100</ID>
<Name>Fridge</Name>
<Description>Latest Refrigerator</Description>
</Table>
<Table>
<ID>200</ID>
<Name>Fridge</Name>
<Description>Another refrigerator</Description>
</Table>
In the example above, I would like to get the child values of Name and Description for the nodes with ID=100. There are around 1000 Table nodes in the xml file.
How can i parse the entire xml and get the Name and Description values for only the nodes with ID equal to 100 ?
So far, i have tried the following code, which could not give what i wanted:
$source = 'Tables.xml';
$xmlstr = file_get_contents($source);
$sitemap = new SimpleXMLElement($xmlstr);
$sitemap = new SimpleXMLElement($source,null,true);
foreach($sitemap as $url) {
if($url->ID == '100')
{
echo 'Name: '.(string)$url->Name.', Description: '.(string)$url->Description.'<br>';
}
}
This should be pretty straightforward if you get all Table tags and loop over them:
// Assuming you already loaded the XML into the SimpleXML object $xml
$names_and_descriptions = array();
foreach ($xml->Table as $t) {
if ($t->ID == 100) {
echo $t->Name . " " . $t->Description . "\n";
// Or stick them into an array or whatever...
$names_and_descriptions[] = array(
'name'=>$t->Name,
'description'=>$t->Description
);
}
}
var_dump($names_and_descriptions);
Related
I have a xml file:
<Epo>
<Doc upd="add">
<Fld name="IC"><Prg><Sen>A01B1/00 <Cmt>(1585, 779)</Cmt></Sen></Prg></Fld>
<Fld name="CC"><Prg><Sen>A01B1/00 <Cmt>(420, 54%)</Cmt>;</Sen><Sen>B25G1/102 <Cmt>(60, 8%)</Cmt>;</Sen><Sen>A01B1/02 <Cmt>(47, 6%)</Cmt></Sen></Prg></Fld></Doc>
<Doc upd="add">
<Fld name="IC"><Prg><Sen>A01B1/02 <Cmt>(3847, 1718)</Cmt></Sen></Prg></Fld>
<Fld name="CC"><Prg><Sen>A01B1/02 <Cmt>(708, 41%)</Cmt>;</Sen><Sen>A01B1/022 <Cmt>(347, 20%)</Cmt>;</Sen><Sen>A01B1/028 <Cmt>(224, 13%)</Cmt></Sen></Prg></Fld></Doc>
</Epo>
I want to get node value, for example : A01B1/00 (1585, 779) - A01B1/00 (420, 54%); B25G1/102 (60, 8%); A01B1/02 (47, 6%)
Then formating them into table's column. how can I do that?
My code:
<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->load('test.xml'); //IPCCPC-epoxif-201905
$xpath = new DOMXPath($doc);
$titles = $xpath->query('//Doc/Fld');
foreach ($titles as $title){
echo $title->nodeValue ."<hr>";
}
?>
I cannot separate evrey node. Please help me.
I've tried to split it down to fetch all the various levels of content, but I think the main problem was just getting the current node text without the child elements text content. Using DOMDocument, the nodeValue is the same as textContent which (from the manual)...
textContent The text content of this node and its descendants.
Using DOMDocument isn't the easiest to use when just accessing a relatively simple hierarchy and requires you to continually make calls (in this case) to getElementsByTagName() to fetch the enclosed elements, the following source shows how you can get at each part of the document using this method...
foreach ( $doc->getElementsByTagName("Doc") as $item ) {
echo "upd=".$item->getAttribute("upd").PHP_EOL;
foreach ( $item->getElementsByTagName("Fld") as $fld ) {
echo "name=".$fld->getAttribute("name").PHP_EOL;
foreach ( $fld->getElementsByTagName("Sen") as $sen ) {
echo trim($sen->firstChild->nodeValue) ." cmt = ".
$sen->getElementsByTagName("Cmt")[0]->firstChild->nodeValue.PHP_EOL;
}
}
}
Using the SimpleXML API can however give a simpler solution. Each level of the hierarchy is accessed using object notation, and so ->Doc is used to access the Doc elements off the root node, and the foreach() loops just work off that. You can also see that using just the element name ($sen->Cmt) will give you just the text content of that node and not the descendants (although you have to cast it to a string to get it's value from the object) ...
$doc = simplexml_load_file("test.xml");
foreach ( $doc->Doc as $docElemnt ) {
echo "upd=".(string)$docElemnt['upd'].PHP_EOL;
foreach ( $docElemnt->Fld as $fld ) {
echo "name=".(string)$fld['name'].PHP_EOL;
foreach ( $fld->Prg->Sen as $sen ) {
echo trim((string)$sen)."=".trim((string)$sen->Cmt).PHP_EOL;
}
}
}
This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 7 years ago.
I need a part of code html by a file from file_get_contents(url)
I do
$variableee = file_get_contents("http://url.com/path/to/file");
echo $variableee;
Ok now in Variableee I've all the url's code.
In this code there is a part that I need. I need a table with class name "table".
Es.
<div>text</div>
<span> text </span>
<table class="table">
<tr><td>Text that I need</td></tr>
</table>
How I can get it?
Sorry for bad english.
If you want the data within PHP itself use the built-in DOM parser,
<?php
$doc = new DOMDocument();
$doc->loadHTML($variableee);
$arr = $doc->getElementsByTagName("table"); // DOMNodeList Object
foreach($arr as $item) { // DOMElement Object
echo $item->nodeValue;
}
?>
EDIT: Parse using the class name with DOMXPath
$doc = new DOMDocument();
$doc->loadHTML($variableee);
$classname = 'table';
$a = new DOMXPath($doc);
$spans = $a->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' $classname ')]");
foreach($spans as $item) { // DOMElement Object
echo $item->nodeValue;
}
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:
Closed 10 years ago.
Possible Duplicate:
foreach and simplexml
I have got my XML document loading correct but I am unsure how I can create a simple foreach were I can have [PictureHref] [Title] and [PriceDisplay] loaded for each item given in the feed.
I cannot find a clear example in the documentation.
XML Example
Currently my PHP code consists of the following:
$mainUrl = 'http://api.trademe.co.nz/v1/Member/{id}/Listings/All.xml';
$xmlFeed = simplexml_load_file($mainUrl);
XML
<Listings xmlns="http://api.trademe.co.nz/v1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<TotalCount>1</TotalCount>
<Page>1</Page>
<PageSize>1</PageSize>
<List>
<Listing>
<ListingId>527496168</ListingId>
<Title>Clifftop Resort style Living with stunning aspect</Title>
<Category>0350-5748-3399-</Category>
<StartPrice>0</StartPrice>
<StartDate>2012-10-26T21:24:47.073Z</StartDate>
<EndDate>2012-12-21T21:24:47.073Z</EndDate>
<ListingLength i:nil="true" />
<HasGallery>true</HasGallery>
<AsAt>2012-10-28T22:48:47.409946Z</AsAt>
<CategoryPath>/Trade-me-property/Residential/For-sale</CategoryPath>
<PictureHref>http://images.trademe.co.nz/photoserver/thumb/10/239043710.jpg</PictureHref>
<RegionId>2</RegionId>
<Region>Auckland</Region>
<Suburb>North Shore</Suburb>
<NoteDate>1970-01-01T00:00:00Z</NoteDate>
<ReserveState>NotApplicable</ReserveState>
<IsClassified>true</IsClassified>
<GeographicLocation>
<Latitude>-36.5681333</Latitude>
<Longitude>174.6936265</Longitude>
<Northing>5951700</Northing>
<Easting>1751547</Easting>
<Accuracy>Address</Accuracy>
</GeographicLocation>
<PriceDisplay>To be auctioned</PriceDisplay>
</Listing>
</List>
</Listings>
All you need is
$url = simplexml_load_file("__YOUR__URL___");
$listing = $url->List->Listing;
echo "<pre>";
echo $listing->PictureHref, PHP_EOL;
echo $listing->Title, PHP_EOL;
echo $listing->PriceDisplay, PHP_EOL;
While I'd recommend the use of DOMDocument instead of SimpleXML, here's how you'd do that in SimpleXML:
$data = array();
foreach($xmlFeed->List as $item) {
$data[] = array(
(string) $item->Listing->PictureHref,
(string) $item->Listing->Title,
(string) $item->Listing->PriceDisplay
);
}
You can see it (sorta, I had to change some things) at CodePad
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.