search
HomeBackend DevelopmentPHP TutorialPHP的xml字符串解析(在线求解)

小弟接触php时间不长,今天遇到个问题就是解析xml字符串,内容是

<?xml version='1.0' encoding='utf-8'?><order_info><user_name>13817969688</user_name><mobile>13817969688</mobile><tel>021-54485454</tel><customer_name>刘先生</customer_name><city_name>上海</city_name><district_name>长宁</district_name><address>新中路999号4栋8楼</address><customer_word>送货前电话联系,谢谢。</customer_word><goods_infos><good><goods_id>51541</goods_id><goods_amount>1</goods_amount></good><good><goods_id>51542</goods_id><goods_amount>3</goods_amount></good></goods_infos></order_info>


$xml=simplexml_load_string($xmlStr);foreach($xml->order_info as $item) {	oreach($item as $k=>$v)	echo "$k $v\n";}

代码是网上找的,但用到我的这个上面行不通,我试了一下,一方面是因为字符串有汉字,另一方面是xml结构跟网上提供的示例不一样,请问亲们这个要怎么解析呢


回复讨论(解决方案)

 header('Content-Type: text/xml');


加上这行代码试试

1、simplexml 会忽略根节点
对于你的示例数据,根节点 order_info 被忽略,所以 $xml->order_info 不存在,所以你不会有输出
打印一级子节点的值应这样写

foreach($xml->children() as $k=>$v) {  if(empty($v)) //这里检查是否有子节点,如有就不打印。这样就跳过了 goods_infos    echo "$k $v\n";}

2、如果是打印 goods_infos 下的 good 子节点,则写作
foreach($xml->goods_infos->good as $item) {  foreach($item as $k=>$v)    echo "$k $v\n";}

3、如果你的程序文件不是 utf-8 的,还应该有
$xmlStr = str_replace("encoding='utf-8'", "encoding='gbk'", $xmlStr);
即将字符集改为真实的字符集
当然打印的结果仍然是 utf-8 的

如果需要遍历所有节点,那么就需要递归

function show_child($xml) {  foreach($xml->children() as $tag=>$item) {    if($item) show_child($item);    else echo "$tag: $item\n";  }}show_child($xml);
user_name: 13817969688
mobile: 13817969688
tel: 021-54485454
customer_name: 刘先生
city_name: 上海
district_name: 长宁
address: 新中路999号4栋8楼
customer_word: 送货前电话联系,谢谢。
goods_id: 51541
goods_amount: 1
goods_id: 51542
goods_amount: 3

1、simplexml 会忽略根节点
对于你的示例数据,根节点 order_info 被忽略,所以 $xml->order_info 不存在,所以你不会有输出
打印一级子节点的值应这样写

foreach($xml->children() as $k=>$v) {  if(empty($v)) //这里检查是否有子节点,如有就不打印。这样就跳过了 goods_infos    echo "$k $v\n";}

2、如果是打印 goods_infos 下的 good 子节点,则写作
foreach($xml->goods_infos->good as $item) {  foreach($item as $k=>$v)    echo "$k $v\n";}

3、如果你的程序文件不是 utf-8 的,还应该有
$xmlStr = str_replace("encoding='utf-8'", "encoding='gbk'", $xmlStr);
即将字符集改为真实的字符集
当然打印的结果仍然是 utf-8 的
非常感谢你的详细解答,但现在遇到个问题是,我的xml文件在simplexml_load_string处理之前是正常的,但处理之后输出发现乱码了,而且转码好像转不过来,我的程序文件是gbk的,所以我加过$xmlStr = str_replace("encoding='utf-8'", "encoding='gbk'", $xmlStr);了

不是说了吗?
当然打印的结果仍然是 utf-8 的
因为 utf-8 是 xml 的工作语言
你需要逐个的对待打印的数据进行转码
比如 echo iconv('utf-6', 'gbk', $v);

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment