Examples:
echo $cd->price;You must use implicit type casting with caution however. There are situations where you might think the string context is implicit but it is not. For example, the following conditional test will fail unexpectedly because a conditional test does not implicitly expect a string, even if one of the two values being compared is a string:
Wrong: if ($artist->name == 'Bonnie Tyler') Right: if ((string)$artist->name == 'Bonnie Tyler')
$artist = $catalog->artist[0]; $retired = $artist['active'];This code fragment retrieves the value of the active attribute for an artist and stores it in the variable $retired.
$cd->price = 10.50; $cd['country'] = 'usa';
$root->asXML();The file will be saved as an ascii text file.
$obj->xpath('path[filter expression]')The path is a path that starts at $obj and returns a group of objects that we want to filter. The filter expression is applied to each object in the group and returns those objects that satisfy the expression. For example, the following query returns all cd objects whose price is greater than or equal to $10:
foreach ($catalog->xpath('cd[price >= 10]') as $qualitycd)The xpath syntax can be a bit tricky. First note that you should use the regular inequality signs rather than their entity representations, as in XSLT. Second, you must always start the query expression with a path, such as 'cd' in the above example. For example, the following code will get an error message from php because the path is missing:
foreach ($catalog->cd->xpath('price >= 10') as $qualitycd)If you want to perform a query on the current node you can type:
foreach ($cd->xpath('./[price >= 10]') as $qualitycd)but this is unnecessarily complicated because all you are doing is asking whether this particular cd has a price greater than or equal to 10. In general you should reserve xpath queries for collections of objects.
// create the document model $catalogDoc = new DOMDocument(); // The DOM parser typically treats whitespace between elements, such as // line breaks, as text. Hence it will create children nodes for these // "text elements", which is annoying. We can stop this behavior by setting // the document's preserveWhiteSpace property to false $catalogDoc->preserveWhiteSpace = false; // The load function reads an xml file and parses it into a tree $catalogDoc->load("cdcatalog.xml"); // The documentElement variable is a pointer to the root object in the tree $catalog = $catalogDoc->documentElement;
$children = $catalog->childNodes;$children points to a nodelist.
$cds = $catalog->getElementsByTagName('cd');Since there are multiple cds, $cds will be a nodelist.
Here are several examples: