Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

PHP Tutorial

PHP HOMEPHP IntroPHP InstallPHP SyntaxPHP CommentsPHP VariablesPHP Echo / PrintPHP Data TypesPHP StringsPHP NumbersPHP CastingPHP MathPHP ConstantsPHP Magic ConstantsPHP OperatorsPHP If...Else...ElseifPHP SwitchPHP LoopsPHP FunctionsPHP ArraysPHP SuperglobalsPHP RegEx

PHP Forms

PHP Form HandlingPHP Form ValidationPHP Form RequiredPHP Form URL/E-mailPHP Form Complete

PHP Advanced

PHP Date and TimePHP IncludePHP File HandlingPHP File Open/ReadPHP File Create/WritePHP File UploadPHP CookiesPHP SessionsPHP FiltersPHP Filters AdvancedPHP Callback FunctionsPHP JSONPHP Exceptions

PHP OOP

PHP What is OOPPHP Classes/ObjectsPHP ConstructorPHP DestructorPHP Access ModifiersPHP InheritancePHP ConstantsPHP Abstract ClassesPHP InterfacesPHP TraitsPHP Static MethodsPHP Static PropertiesPHP NamespacesPHP Iterables

MySQL Database

MySQL DatabaseMySQL ConnectMySQL Create DBMySQL Create TableMySQL Insert DataMySQL Get Last IDMySQL Insert MultipleMySQL PreparedMySQL Select DataMySQL WhereMySQL Order ByMySQL Delete DataMySQL Update DataMySQL Limit Data

PHP XML

PHP XML ParsersPHP SimpleXML ParserPHP SimpleXML - GetPHP XML ExpatPHP XML DOM

PHP - AJAX

AJAX IntroAJAX PHPAJAX DatabaseAJAX XMLAJAX Live SearchAJAX Poll

PHP Examples

PHP ExamplesPHP CompilerPHP QuizPHP ExercisesPHP ServerPHP SyllabusPHP Study PlanPHP Certificate

PHP Reference

PHP OverviewPHP Array
array()array_change_key_case()array_chunk()array_column()array_combine()array_count_values()array_diff()array_diff_assoc()array_diff_key()array_diff_uassoc()array_diff_ukey()array_fill()array_fill_keys()array_filter()array_flip()array_intersect()array_intersect_assoc()array_intersect_key()array_intersect_uassoc()array_intersect_ukey()array_key_exists()array_keys()array_map()array_merge()array_merge_recursive()array_multisort()array_pad()array_pop()array_product()array_push()array_rand()array_reduce()array_replace()array_replace_recursive()array_reverse()array_search()array_shift()array_slice()array_splice()array_sum()array_udiff()array_udiff_assoc()array_udiff_uassoc()array_uintersect()array_uintersect_assoc()array_uintersect_uassoc()array_unique()array_unshift()array_values()array_walk()array_walk_recursive()arsort()asort()compact()count()current()each()end()extract()in_array()key()krsort()ksort()list()natcasesort()natsort()next()pos()prev()range()reset()rsort()shuffle()sizeof()sort()uasort()uksort()usort()
PHP CalendarPHP Date
checkdate()date_add()date_create_from_format()date_create()date_date_set()date_default_timezone_get()date_default_timezone_set()date_diff()date_format()date_get_last_errors()date_interval_create_from_date_string()date_interval_format()date_isodate_set()date_modify()date_offset_get()date_parse_from_format()date_parse()date_sub()date_sun_info()date_sunrise()date_sunset()date_time_set()date_timestamp_get()date_timestamp_set()date_timezone_get()date_timezone_set()date()getdate()gettimeofday()gmdate()gmmktime()gmstrftime()idate()localtime()microtime()mktime()strftime()strptime()strtotime()time()timezone_abbreviations_list()timezone_identifiers_list()timezone_location_get()timezone_name_from_abbr()timezone_name_get()timezone_offset_get()timezone_open()timezone_transitions_get()timezone_version_get()
PHP DirectoryPHP ErrorPHP ExceptionPHP Filesystem
basename()chgrp()chmod()chown()clearstatcache()copy()delete()dirname()disk_free_space()disk_total_space()diskfreespace()fclose()feof()fflush()fgetc()fgetcsv()fgets()fgetss()file()file_exists()file_get_contents()file_put_contents()fileatime()filectime()filegroup()fileinode()filemtime()fileowner()fileperms()filesize()filetype()flock()fnmatch()fopen()fpassthru()fputcsv()fputs()fread()fscanf()fseek()fstat()ftell()ftruncate()fwrite()glob()is_dir()is_executable()is_file()is_link()is_readable()is_uploaded_file()is_writable()is_writeable()lchgrp()lchown()link()linkinfo()lstat()mkdir()move_uploaded_file()parse_ini_file()parse_ini_string()pathinfo()pclose()popen()readfile()readlink()realpath()realpath_cache_get()realpath_cache_size()rename()rewind()rmdir()set_file_buffer()stat()symlink()tempnam()tmpfile()touch()umask()unlink()
PHP FilterPHP FTPPHP JSONPHP KeywordsPHP LibxmlPHP MailPHP MathPHP MiscPHP MySQLiPHP NetworkPHP Output ControlPHP RegExPHP SimpleXMLPHP StreamPHP String
addcslashes()addslashes()bin2hex()chop()chr()chunk_split()convert_cyr_string()convert_uudecode()convert_uuencode()count_chars()crc32()crypt()echo()explode()fprint()get_html_translation_table()hebrev()hebrevc()hex2bin()html_entity_decode()htmlentities()htmlspecialchars_decode()htmlspecialchars()implode()join()lcfirst()levenshtein()localeconv()ltrim()md5()md5_file()metaphone()money_format()nl_langinfo()nl2br()number_format()ord()parse_str()print()printf()quoted_printable_decode()quoted_printable_encode()quotemeta()rtrim()setlocale()sha1()sha1_file()similar_text()soundex()sprintf()sscanf()str_getcsv()str_ireplace()str_pad()str_repeat()str_replace()str_rot13()str_shuffle()str_split()str_word_count()strcasecmp()strchr()strcmp()strcoll()strcspn()strip_tags()stripcslashes()stripslashes()stripos()stristr()strlen()strnatcasecmp()strnatcmp()strncasecmp()strncmp()strpbrk()strpos()strrchr()strrev()strripos()strrpos()strspn()strstr()strtok()strtolower()strtoupper()strtr()substr()substr_compare()substr_count()substr_replace()trim()ucfirst()ucwords()vfprintf()vprintf()vsprintf()wordwrap()
PHP Variable HandlingPHP XML ParserPHP ZipPHP Timezones

PHPXML DOM Parser


The built-in DOM parser makes it possible to process XML documents in PHP.


The XML DOM Parser

The DOM parser is a tree-based parser.

Look at the following XML document fraction:

<?xml version="1.0" encoding="UTF-8"?>
<from>Jani</from>

The DOM sees the XML above as a tree structure:

  • Level 1: XML Document
  • Level 2: Root element: <from>
  • Level 3: Text element: "Jani"

Installation

The DOM parser functions are part of the PHP core. There is no installation needed to use these functions.


The XML File

The XML file below ("note.xml") will be used in our example:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


Load and Output XML

We want to initialize the XML parser, load the xml, and output it:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
?>

The output of the code above will be:

Tove Jani Reminder Don't forget me this weekend!

If you select "View source" in the browser window, you will see the following HTML:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The example above creates a DOMDocument-Object and loads the XML from "note.xml" into it.

Then the saveXML() function puts the internal XML document into a string, so we can output it.


Looping through XML

We want to initialize the XML parser, load the XML, and loop through all elements of the <note> element:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item) {
  print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>

The output of the code above will be:

#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =

In the example above you see that there are empty text nodes between each element.

When XML generates, it often contains white-spaces between the nodes. The XML DOM parser treats these as ordinary elements, and if you are not aware of them, they sometimes cause problems.


If you want to learn more about the XML DOM, please visit ourXML tutorial.



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp